2017-02-15 77 views
0

我想創建一個可重用的網絡服務組件,它將負責Item的CRUD請求。Typescript通用約束擴展了其他通用類型

讓「S說我CatService要申請的cats列表,那麼它可以有一個restService實例,它可以使用它的列表,創建,更新,刪除...:

private restService:RestListService<Cat[]> = RestListService(); 
... 
restService.list(urlToGetCats).then(cats => console.log(listdata)); 
... 
restService.update(urlToUpdateACat, updatedCat); 

我。實現了這個通用組件,但它不夠安全類聲明的樣子:

export class RestListService<T extends Array<Identifiable>> { 

    private dataSubject$: BehaviorSubject<T> = null; 

    list(url: string): Promise<T> { } 

    // PROBLEM: I cannot specify the `savingInstance` & the returned Promise type: 
    update(updateURL: string, savingInstance: Identifiable): Promise<Identifiable> { } 

} 

理想情況下,我會做一些這樣的陣列中引入通用V作爲項目的類型,使AR (以及整個班級)更安全:

export class RestListService<T extends Array<V extends Identifiable>> { 

    //Here the Promise is type safe: 
    update(updateURL: string, savingInstance: Identifiable): Promise<V> { } 

} 

但目前尚不允許(如我所見)。

在這種情況下,我能以某種方式解決類型安全問題嗎?

感謝您的幫助!

回答

0

你的意思是這樣嗎?

​​