簡體   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