TypeScript class類相容

admin發表於2019-04-27

TypeScript類和介面的相容性非常類似,但是類分例項部分和靜態部分。

比較兩個類型別資料時,只有例項成員會被比較,靜態成員和建構函式不會比較。

程式碼例項如下:

[typescript] 純文字檢視 複製程式碼
class Antzone {
    webName: string;
    constructor(address: string, age: number) { }
}
 
class Other {
    webName: string;
    constructor(age: number) { }
}
 
let ant: Antzone=new Antzone("青島市南區",4);
let other: Other;
 
other = ant; //賦值成功

賦值成功,反過來也是如此,建構函式是否相容不會影響。再來看一段程式碼例項:

[typescript] 純文字檢視 複製程式碼
class Antzone {
    webName: string;
    constructor(address: string, age: number) { }
}
 
class Other {
    webName: string;
    target:string;
    constructor(age: number) { }
}
 
let ant: Antzone=new Antzone("青島市南區",4);
let other: Other;
 
other = ant; //賦值報錯

因為Other中的所有例項成員必須在Antzone中找到對應的成員。

類私有成員問題:

私有成員會影響相容性判斷,如果目標型別包含一個私有成員,那麼源型別必須包含來自同一個類的這個私有成員。 

允許子類賦值給父類,但是不能賦值給其它有同樣型別的類。

關於私有成員可以參閱TypeScript 類訪問修飾符一章節。

[typescript] 純文字檢視 複製程式碼
class Antzone {
    webName: string;
    constructor(address: string, age: number) { }
}
 
class Other {
    private webName: string;
    constructor(age: number) { }
}
 
let ant: Antzone=new Antzone("青島市南區",4);
let other: Other;
 
other = ant; //賦值報錯

由於是Other中的webName是私有成員,所以會報錯。

相關文章