undefined
undefined

Reputation: 6844

RxJS typescript understanding the generic types

From RxJS docs we can learn that we can create custom operators with the following code:

const takeEveryNthSimple = (n: number) => <T>(source: Observable<T>) =>
  source.pipe(filter((value, index) => index % n === 0 ))

I want to understand what is the type of generics in this case <T>(source: Observable<T>).

Please help.

Upvotes: 1

Views: 1080

Answers (1)

Baruch
Baruch

Reputation: 2428

Look at generic types as a way to have the same function be able to return any type that is passed.

For example, a function that does a get request.

function doGet<T>(endpoint: string): Observable<T> {
  return Observable.of(fetch(endpoint));
}

This function will return an observable of type T;

Now, let's say you have a REST api that you can get Posts, Users, Tags. You can use this function with a type definition as such

interface Posts {
  //...
}

interface Users {
  //...
}

interface Tags {
  //...
}

doGet<Posts>('/api/posts') => Observable<Posts>;
doGet<Users>('/api/users') => Observable<Users>;
doGet<Tags>('/api/tags') => Observable<Tags>;

In the example you provide, the Observable that's being passed to the nested function will be of type T that is defined in the generic type.

Hopefully this is clear and answers your question.

Upvotes: 3

Related Questions