属性 类型检查后类型不存在
Property does not exist on type after type check
在下面的代码中,我尝试在类型检查后使用 class 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
returns 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
}
}
在下面的代码中,我尝试在类型检查后使用 class 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
returns 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
}
}