Member-only story

RxJS: How to Use Type Guards with Observables

Nicholas Jamieson
3 min readSep 11, 2017

--

Photo by Tanner Van Dera on Unsplash

Since version 1.6, TypeScript has supported user-defined type guards.

When composing an observable, a type guard can be used to ensure that the correct type is inferred at compile time and that the received value is validated at run time. With run-time validation, problems can be caught early and descriptive errors can be thrown from locations close to where values are received — these are easier to diagnose than cannot-read-property-of-undefined errors that are thrown from seemingly unrelated locations.

What is a type guard?

A user-defined type guard is a function that performs a run-time check to evaluate its returned type predicate.

Let’s look at an example that uses the following interface:

A basic type guard that can be used to determine whether or not a value is compatible with the Person interface looks something like this:

--

--

Nicholas Jamieson
Nicholas Jamieson

Written by Nicholas Jamieson

RxJS core team member; front-end developer; mentor; speaker; open-source contributor

Responses (4)