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!