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