2015-08-22 31 views

回答

1

此限制是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類型。