Reputation: 2332
I would like to create a reusable network service component, which would be responsible for CRUD requests of an Item
.
Let"s say my CatService
want to request a list of cats
, then it can have a restService
instance and it can use it for list, create, update, delete...:
private restService:RestListService<Cat[]> = RestListService();
...
restService.list(urlToGetCats).then(cats => console.log(listdata));
...
restService.update(urlToUpdateACat, updatedCat);
I implemented this generic components, but it not safe enough. The class declaration looks like:
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> { }
}
Ideally, I would do something like introduce a generic V
as the type of the items in the array to make the array (and the whole class) more typesafe:
export class RestListService<T extends Array<V extends Identifiable>> {
//Here the Promise is type safe:
update(updateURL: string, savingInstance: Identifiable): Promise<V> { }
}
But it's not permitted at the moment (as I see).
Can I somehow solve the type safety in this situation?
Thanks for your help!
Upvotes: 3
Views: 978
Reputation: 37604
Do you mean like this?
export class RestListService<V extends Identifiable, T extends Array<V>> {
//Here the Promise is type safe:
update(updateURL: string, savingInstance: Identifiable): Promise<V> { }
}
Upvotes: 3