2016-07-11 64 views
0

想象一下簡單的CollectionStore,它具有創建和更新記錄的方法。 create()接受一組屬性並返回與添加的id屬性相同的集合。 update接受相同結構的集合,但需要定義id屬性。Typescript:獲取類型並在通用接口中返回聯合類型

如何在Typescript中表示create()函數接受某種類型T並返回T & {id: string}

我希望像要表達的模式:

interface CollectionStore<T> { 
    updateRecord(T & {id: string}): void; 
    createRecord(T): T & {id: string}; 
} 

但是上面的代碼是無效的。請幫助=)

回答

1

你在你如何使用聯合類型是對的,但你沒有提供的功能PARAMS這就是爲什麼你會得到錯誤的名字,它應該是:

interface CollectionStore<T> { 
    updateRecord(record: T & { id: string }): void; 
    createRecord(record: T): T & { id: string }; 
} 

而且然後:

interface MyRecord { 
    key: string; 
} 

let a: CollectionStore<MyRecord> = ...; 

a.updateRecord({ key: "key", id: "id" }); 
a.createRecord({ key: "key" }); 

code in playground

你有另一種選擇是隻是有一個基本接口,其中id屬性是可選的記錄:

interface Record { 
    id?: string; 
} 

interface CollectionStore<T extends Record> { 
    updateRecord(record: T): void; 
    createRecord(record: T): T; 
} 

但是那麼你失去了強制執行的能力updateRecord返回一個帶有id的對象。