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

时间:2019-05-12 11:32:01

标签: javascript typescript types typechecking

在以下代码中,我尝试在进行类型检查后使用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

1 个答案:

答案 0 :(得分:4)

问题在于,t1是用let定义的,这意味着在运行时,调用test上的t2函数时,可能已经已经更改并且不再是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
    }
}