Top 3 RxJS operators overloads


If you’ve been using the RxJS library for some time, you must have stumbled across operators like: distinctUntilChanged, filter and first. But, have you ever used powerful, overloaded versions?

In this post I’ll cover the aforementioned operators’ overloads.


distinctUntilChanged

Widely known version 📕

Overloaded version 🌟

You can provide a compare function which determines whether a next notification from the source stream is identical to the previously emitted item.


filter

Widely known version 📕

A next notification from the source stream will have an inferred type of string | number. You may expect that due to filtering only string values an attempt to access the length property will be a valid operation. However, you’re wrong, since the filter operator is not a type guard.

Overloaded version 🌟

It’s the type predicate (item is string) defined as a return type of the provided predicate function that makes the filter operator a type guard here. Consequently, item within the map operator’s project function will have a string type inferred. Detailed explanation can be found here.


first

Widely known version 📕

Overloaded version 🌟

If you’re interested in the first next notification satisfying a given predicate function, you can pass the function to the first operator. It’s a nice alternative to applying the filter operator followed by the first operator in a non-overloaded version or the take(1) operator.

Wojciech Trawiński

Written by

Doing awesome things using JavaScript

JavaScript everyday

Improve your JavaScript skills everyday!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade