When using TypeScript with strict
mode enabled on the TypeScript playground, I encountered an interesting case:
type Foo = { a: number; b: number; }
class Bar {
#a?: Foo;
bar() {
const a = this.#a?.a;
if (!a) {return;}
// Error: Object is possibly 'undefined'.
const b = this.#a.b;
}
bar2() {
const obj = this.#getFoo();
const a = obj?.a;
if (!a) {return;}
// No error:
const b = obj.b;
console.log(b);
}
#getFoo() : Foo | undefined {
return undefined;
}
}
I wonder why TypeScript correctly identifies that obj.b
cannot be undefined
in bar2()
, but not for this.#a.b
in bar()
. Is there a logical explanation that I am missing?
In bar()
, assigning const tmp = this.#a
also compiles successfully.
UPDATE: It seems like the issue is related to the mutability of a variable. If I use let obj = this.#getFoo()
, the error occurs for obj
as well.