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> { }
}
但目前尚不允许(如我所见)。
在这种情况下,我能以某种方式解决类型安全问题吗?
感谢您的帮助!