[英]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.