Type Guards

This lesson introduces the concept of type guards.

Overview

Type guard is not really a type so much as it is a mechanism that narrows types.

TypeScript soars at analyzing your code and deducing information based on it. Oftentimes, TypeScript can analyze a conditional expression (or an if statement) and narrow the type of the tested value inside the branches of the condition. We’ve already seen this happen with discriminated unions. This mechanism is referred to as type guard.

Nullable type guard

We’ve already seen the nullable type guard in action when discussing strictNullChecks. Nullable type guard removes optionality from the type of some value if this value is previously tested for nullability. In the below example, if the name is truthy (i.e., not null or undefined), its type is narrowed to string inside the positive branch of the if statement.

Get hands-on with 1400+ tech skills courses.