1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In the example the provides github.com/ReactiveX/rxjs/blob/master/doc/…, I can't see they provide the T type like you did, so what is the type?
Tis just the name that was given to the generic type. Think of it as an undeclared variable, once you use the function and give it a type signature, this signature will be used anywhere the function uses <T>. People usually use T as a reference to type, but you could use any letter you like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.