Member-only story
RxJS: How to Use Type Guards with Observables
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: