Course contentsShow
← TypeScript
Lesson 398 of 1,7969. Union TypesFree lesson

Type Predicates for Custom Narrowing

Writing user-defined type guards that return 'value is Type' for complex unions.

Type Predicates for Custom Narrowing

What you'll learn: How to write your own type guard functions that narrow complex union types beyond what built-in operators can handle.


The Problem with Complex Unions

Sometimes you have union types where typeof, in, and instanceof aren't enough. Imagine checking if an object has valid email properties, or distinguishing between similar shapes based on business logic rather than simple property existence.

Writing Type Predicates

A type predicate is a special return type for functions that tells TypeScript: "If this function returns true, then the value is definitely this specific type."

The syntax uses value is Type:

type Cat = { meow: () => void };
type Dog = { bark: () => void };

function isCat(animal: Cat | Dog): animal is Cat {
  return 'meow' in animal;
}

const pet: Cat | Dog = getPet();

if (isCat(pet)) {
  pet.meow(); // TypeScript knows pet is Cat here
} else {
  pet.bark(); // TypeScript knows pet is Dog here
}

Why This Matters

Without animal is Cat, the function would just return boolean, and TypeScript wouldn't narrow the type inside your if block. The type predicate creates a contract: you promise that when the function returns true, the value matches that type.

The Responsibility

Type predicates are powerful but dangerous. You are responsible for the logic being correct. TypeScript trusts your assertion. If your check is wrong, you'll get runtime errors despite type safety.

Key Takeaway: Type predicates let you write custom narrowing logic for complex unions by returning value is Type, giving you full control over type narrowing beyond built-in operators.