Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic return type of function in Typescript

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?

like image 924
Param Singh Avatar asked May 23 '16 08:05

Param Singh


People also ask

How do I specify a return type of function in TypeScript?

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.

What is the default return type of a function in TypeScript?

The function's return type is string.

What are the function of generic types in TypeScript?

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.


1 Answers

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.

like image 64
toskv Avatar answered Oct 12 '22 12:10

toskv