TypeScript

User-Defined Type Guards

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When TypeScript can't narrow a union for you, write a `x is T` predicate. Inside any block where the guard returns true, the compiler knows the narrower type.
TypeScript
Raw
interface Cat { kind: 'cat'; meow(): void }
interface Dog { kind: 'dog'; bark(): void }
type Animal = Cat | Dog;

function isCat(a: Animal): a is Cat {
  return a.kind === 'cat';
}

function makeSound(a: Animal) {
  if (isCat(a)) {
    a.meow();          // a is narrowed to Cat
  } else {
    a.bark();          // a is narrowed to Dog
  }
}

// Works for arbitrary "is non-null" checks too:
function isPresent<T>(x: T | null | undefined): x is T {
  return x !== null && x !== undefined;
}

const nums: number[] = [1, null, 2, undefined, 3].filter(isPresent);
// nums: number[] — null/undefined filtered out at the type level
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.