Type Predicates for Union Narrowing
What you'll learn: How to use type predicates to reliably distinguish between different members of a union type.
The Problem with Union Types
When you have a union type like Cat | Dog, TypeScript only lets you access properties common to both types. You need to narrow the union to access type-specific properties, and type predicates give you a powerful, reusable way to do this.
Using Type Predicates to Check Discriminant Properties
A discriminant property is a unique property that exists on one union member but not others (or has a unique literal value). Type predicates let you check these properties in a clean, reusable function:
type Cat = { species: 'cat'; meow: () => void };
type Dog = { species: 'dog'; bark: () => void };
type Pet = Cat | Dog;
function isCat(pet: Pet): pet is Cat {
return pet.species === 'cat';
}
function handlePet(pet: Pet) {
if (isCat(pet)) {
pet.meow(); // ✓ TypeScript knows pet is Cat here
} else {
pet.bark(); // ✓ TypeScript knows pet is Dog here
}
}
The isCat function checks the discriminant property species. Because we used a type predicate (pet is Cat), TypeScript remembers the narrowing result throughout your code.
Why This Matters
Without the type predicate, you'd need to repeat the pet.species === 'cat' check everywhere. With it, you've created a reusable narrowing function that keeps your code DRY and type-safe.
Key Takeaway: Type predicates let you encapsulate discriminant property checks into reusable functions that TypeScript trusts for union narrowing, making your union handling cleaner and more maintainable.