Attempting to narrow down a type in TypeScript:
const result = await fetch('example.com')
if (typeof result === "object" && "errors" in result) {
console.error(result.errors);
}
To clarify, the type of result before the if condition should be unknown
.
However, I encounter error
TS2339: Property 'errors' does not exist on type 'object'.
It seems like TypeScript is ignoring the in
keyword. I included typeof result === "object"
to verify the use of in
in this context.
Interestingly, my IDE does not flag any issues with this code:
if (typeof result === "object" && "errors" in result) {
console.error(result["errors"]);
}
However, TypeScript does not seem to check this since there are no complaints with this code either:
if (typeof result === "object" && "errors" in result) {
console.error(result["nothere"]);
}
Any insights on this matter?