Typescript 泛型约束扩展了其他泛型类型

Typescript generic constraint extends other generic type

我想创建一个可重用的网络服务组件,它将负责 Item.

的 CRUD 请求

假设我的 CatService 想要请求 cats 的列表,那么它可以有一个 restService 实例,并且可以将其用于列表、创建、更新、删除...:

private restService:RestListService<Cat[]> = RestListService();
...
restService.list(urlToGetCats).then(cats => console.log(listdata));
...
restService.update(urlToUpdateACat, updatedCat);

我实现了这个通用组件,但它不够安全。 class 声明如下:

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 作为数组中项目的类型,以使数组(以及整个 class)更加类型安全:

export class RestListService<T extends Array<V extends Identifiable>> {

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

}

但目前不允许(据我所知)。

我能以某种方式解决这种情况下的类型安全问题吗?

感谢您的帮助!

你是这个意思吗?

export class RestListService<V extends Identifiable, T extends Array<V>> {

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

}