2
一般而言,TypeScript
中的類型爲structural
。但是,根據The TypeScript
manual,當測試兩個類的兼容性時,私有屬性需要來自同一層次。這個限制的原因是什麼?類型比較中的私有類屬性
一般而言,TypeScript
中的類型爲structural
。但是,根據The TypeScript
manual,當測試兩個類的兼容性時,私有屬性需要來自同一層次。這個限制的原因是什麼?類型比較中的私有類屬性
此限制是create unmatchable types in TypeScript的唯一途徑。
您可以創建代表共享類型,如果你需要(從鏈接的文章取碼)的接口...
interface GeneralId {
getId() : number;
}
class CustomerId {
constructor(private id: number) {}
getId() { return this.id; }
}
class ProductId {
constructor(private id: number) {}
getId() { return this.id; }
}
function nonSpecificMethod(id: GeneralId) {
//...
}
var id1 = new CustomerId(1);
var id2 = new ProductId(2);
// Type passes
nonSpecificMethod(id1);
// Type passes
nonSpecificMethod(id2);
在這個例子中,一個CustomerId
不能代替ProductId
的使用(這是創建這種包裝類的要點)。如果希望允許它們互換,則可以使用GeneralId
類型。