RxJS and TypeScript: `pipe`
Explore how to type the RxJS pipe function in TypeScript. Understand function overloads, operator typings, and how the input and output observable types connect in a pipe sequence, gaining insight into advanced TypeScript and RxJS integration.
We'll cover the following...
Overview
If you’re familiar with the RxJS library, you should be accustomed with the concept of pipeable operators. It’s a mechanism of composing operators (applying an operator on top of other operators) that replaced chained method calls (stream$.map(...).filter(...)) to make the library tree-shakable. It’s based on the idea of function composition from functional programming. Looking into how pipe is typed is a good exercise in advanced typing.
What is piping?
First, let’s look at some examples of using pipe.
const number$ = of(1, 2, 3, 4, 5).pipe(
filter(x => x % 2 === 0),
map(x => x * x)
);
const response$ = fromEvent(button, 'click').pipe(
debounceTime(500),
tap(() => { console.log('fetching data...'); }),
switchMap(()=> fetch(`http://example.com/api/status`)),
switchMap(response => response.json()),
catchError(() => empty())
);
As you can see, pipe can be called ...