Reputation: 9672
On our Angular project, we use Typescript (2.2.2). I struggle with generics but I think the solution must be simple.
We have a simple service making a http call:
getUsers(): Observable<any> {
return this._service.http.get('/api/users').map(...)
}
getItems(): Observable<any> {
return this._service.http.get('/api/items').map(...)
}
Both requests return an object with this format (example):
User:
{
count: 1,
skip: 0,
take: 10,
objects: [
{ name: 'Jo', age: 24 },
{ name: 'Jane', age: 42 }
]
}
Item:
{
count: 1,
skip: 0,
take: 10,
objects: [
{ id: '54qds44', description: 'a great description' },
{ id: '987azex', description 'another description' }
]
}
I want to replace any
type with the kind of actual exact model we have returned.
Since I have common parts in ALL my responses, I imagined doing this:
// I could be able to use this app wide
class GenericAPIResponseList<T> = {
count: number;
skip: number;
take: number;
objects: <T[]>
};
// And special models in this particular service
class User = {
name: string;
age: number;
}
class Item = {
id: string;
description: string;
}
Then in my service:
getUsers(): Observable<GenericAPIResponseList<User>>
getItems(): Observable<GenericAPIResponseList<Item>>
But it seems this kind of syntax is incorrect for this "generic model containing a generic model".
How can I write this "generic model accepting a list of another model", then place it in my Observable<>
return definition?
I read about Interfaces or Extends but I'm kind of lost.
Upvotes: 0
Views: 162
Reputation: 1317
you got the point, but you have some minor syntax issues :) Try the following:
// I could be able to use this app wide
class GenericAPIResponseList<T> {
count: number;
skip: number;
take: number;
objects: T[];
}
// And special models in this particular service
class User {
name: string;
age: number;
}
class Item {
id: string;
description: string;
}
function getUsers(): Observable<GenericAPIResponseList<User>> {
return this._service.http.get('/api/users').map(...);
}
function getItems(): Observable<GenericAPIResponseList<Item>> {
return this._service.http.get('/api/items').map(...);
}
Upvotes: 1