Reputation: 63
I have a Typescript behaviour that I don't undestand, and I would like to have your input on it.
The compiler throws me an "Object is possibly 'null'" error even if there is a type check before.
Here is a simplified example:
class Bar {
public a: string
}
class Foo {
public bar: Bar | null
}
function functionDoingSomeStuff(callback: any) {
callback()
}
const foo = new Foo()
if (!foo.bar) {
return new Error()
}
console.log(foo.bar.a) // no compiler error thanks to the previous if
if (foo.bar) {
functionDoingSomeStuff(() => {
console.log(foo.bar.a) // a compiler error
})
console.log(foo.bar.a) // no compiler error
}
So why is the compiler warning me if I access to the possibly null property inside a function call, even if the catching if checks it?
Thanks in advance!
Upvotes: 6
Views: 976
Reputation: 276085
This is by design. TypeScript doesn't assume type guards remain active in callbacks as making this assumption is dangerous.
Capture the variable locally to ensure it doesn't get changed externally and TypeScript can easily understand that.
if (foo.bar) {
const bar = foo.bar;
functionDoingSomeStuff(() => {
console.log(bar.a) // no compiler error
})
}
Upvotes: 8