2017-02-15 56 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

你的意思是这样吗?

​​