If I create an instance function that checks for a non-null property in TypeScript, I encounter an error stating 'Object possibly null' when using the function in a conditional statement. However, if I directly check for null, the error does not appear. How can I resolve this issue?
type SomeType = {
someFunc: Function;
}
class A {
bar: SomeType | null;
constructor() {
this.bar = null;
}
hasBar() {
return this.bar !== null;
}
}
const a = new A();
if (a.hasBar()) {
a.bar.someFunc(); // Throws object possibly null error
}
if (a.bar !== null) {
a.bar.someFunc(); // Does not throw any errors
}
Access TypeScript playground Here (Enable strictNullChecks in options)