我希望创建一个可重用的网络服务组件,负责处理Item
的CRUD请求。
假设我的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
作为数组中项的类型一样,使数组(和整个类)更加类型安全:
export class RestListService<T extends Array<V extends Identifiable>> {
//Here the Promise is type safe:
update(updateURL: string, savingInstance: Identifiable): Promise<V> { }
}
但目前不允许这样做(据我所见)。
在这种情况下,我是否可以解决类型安全的问题?
谢谢你的帮助!