Tutorial hero
Lesson icon

Type Guards

Originally published September 08, 2022 Time 2 mins

Learn how to use TypeScript type guards. I am actually going to publish a video on this next week, but I am going to show you a quick example now where type guards can be extremely useful with observables.

Let’s take a look a this example:

type guards being extremely useful with observables

I have a user stream that can either emit a user object or null. I then have a getUser method that I want to return a stream that only emits valid users, not null values.

It’s easy enough to do this with the filter RxJS operator:

filter RxJS operator

The only problem is that, although we have filtered out any null values, TypeScript does not know that the values in this stream won’t be null now.

This is where we can use a type guard. The basic idea is that we can assign a type guard to a function that evaluates a predicate (i.e. it will evaluate to true or false). We use this type guard to tell TypeScript what type the data should be if the predicate returns true.

Our filter already uses a predicate to check for non null users - the filter function will return true or false. That means we can easily assign a type guard to this function:

filter function when returning user

Now we are saying that if the value passed into the filter (user) passes the check, it should be assigned the User type (user is User).

This is a reasonably basic but extremely useful example. In the video next week, we are going to dive deeper into using type guards in other situations and also creating a type guard that uses TypeScript generics.

Learn to build modern Angular apps with my course