繁体   English   中英

类型检查后类型上的属性不存在

[英]Property does not exist on type after type check

在下面的代码中,我尝试在类型检查后使用Test类的实例。

main.ts

class Test {
    x: number = 0;
    test() {}
}

let t1: Test | number = new Test();

if (t1 instanceof Test) {
    console.log(t1.x); // works
    let t2 = new Test();
    t2.test = function() {
        this.x = t1.x; // doesn't work
    }
}

运行tsc main.ts我得到:

main.ts:12:21 - error TS2339: Property 'x' does not exist on type 'number | Test'.
  Property 'x' does not exist on type 'number'.

12         this.x = t1.x; // doesn't work
                       ~


Found 1 error.

tsc --version返回Version 3.4.5

问题是, t1是用let定义的,这意味着在运行时中,调用t2上的test函数时,它可能已经更改并且不再是Test类型的(嗯,不在代码段中,而是从从编译器的角度来看,可以在函数定义后编写一些代码)。

如果将定义更改为const ,则可以正常工作:

class Test {
    x: number = 0;
    test() {}
}

const t1: Test | number = new Test();

if (t1 instanceof Test) {
    console.log(t1.x); // works
    let t2 = new Test();
    t2.test = function() {
        this.x = t1.x; // works fine
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM