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> { }
}
但目前尚不允許(如我所見)。
在這種情況下,我能以某種方式解決類型安全問題嗎?
感謝您的幫助!