TypeScript 给出编译错误“对象可能是‘未定义’。”但仅限于类变量而不是作用域变量

问题描述 投票:0回答:1

在启用了

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
也会出现错误。

typescript compiler-errors undefined
1个回答
0
投票

bar()
中,TS不会自动识别可选链接后
this.#a
可能为非空,从而导致访问
this.#a.b
时出错。在
bar2()
中,通过将
this.#getFoo()
的结果分配给obj并在使用
obj?.a
之前检查
obj.b
,TS可以跟踪
obj
的可空性,使其能够理解如果
obj?.a
不是未定义的,那么
obj.b
也可以安全访问。

© www.soinside.com 2019 - 2024. All rights reserved.