I'm new to ts but I've learnt a little about the concept of generics in java. The query is that I have three functions : searchTrack, searchAlbum, searchArtist
searchTrack(query: string): Observable<Track[]> {
return this.search(query, 'track');
}
searchArtist(query: string): Observable<Artist[]> {
return this.search(query, 'artist');
}
searchAlbum(query: string): Observable<Album[]> {
return this.search(query, 'album');
}
I want a general function 'search' in this class that takes the query and the type of entity and returns an Observable of collection of a specific entity type. I'm stuck here. How can I work with generics to specify a generic return type of a function.
search(query: string, type: string): Observable<Array<T>> {
return this.query(`/search`, [
`q=${query}`,
`type=${type}`
]);
}
Is there any way I can achieve this?
Try using the Array class instead of []. Also define a generic T type on the search function.
search<T>(query: string, type: string): Observable<Array<T>> {
return this.query(`/search`, [
`q=${query}`,
`type=${type}`
]);
}
You should be able to call it like this:
let result = search<Artist>('someQuery', 'artist');
You can find more about generics in typescript in the Generics chapter in the handbook here.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments