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?
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
The function's return type is string.
Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With