Custom Type Guards

This lesson explains custom type guards and how they're useful.

We'll cover the following

Overview

TypeScript lets you define your own type guards. A custom type guard is a Boolean-returning function that can additionally assert something about the type of its parameter. If the function is called in the context of a conditional expression, the type of the passed value is narrowed to the asserted type inside the positive branch of the conditional.

Below, you can see an example of an isArticle type guard. It’s a function that takes an object and checks if it’s an instance of Article by checking for the presence of certain properties. Later, when the function is used inside the if statement, the type of body is narrowed to Article in the first branch of the conditional statement.

Get hands-on with 1200+ tech skills courses.