TypeScript泛型约束扩展其他泛型类型。

3

我希望创建一个可重用的网络服务组件,负责处理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> { }

}

但目前不允许这样做(据我所见)。

在这种情况下,我是否可以解决类型安全的问题?

谢谢你的帮助!

1个回答

3
你是指像这样吗?
export class RestListService<V extends Identifiable, T extends Array<V>> {

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

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接