RxJS and TypeScript: `pipe`
This lesson looks into typing the `pipe` function in RxJS as an example of typing complex variadic functions.
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 ...