在启用了
strict
的 TypeScript 中(TypeScript Playground):
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;
}
}
为什么TS在
bar2()
中正确理解obj.b
不能是undefined
;但不是 this.#a.b
中的 bar()
?我是否缺少逻辑案例?
在
bar()
中,如果我分配const tmp = this.#a
,它也会成功编译。
更新:显然它与变量的可变性有关。如果我使用
let obj = this.#getFoo()
,obj
也会出现错误。
在
bar()
中,TS不会自动识别可选链接后this.#a
可能为非空,从而导致访问this.#a.b
时出错。在bar2()
中,通过将this.#getFoo()
的结果分配给obj并在使用obj?.a
之前检查obj.b
,TS可以跟踪obj
的可空性,使其能够理解如果obj?.a
不是未定义的,那么obj.b
也可以安全访问。