Type guards

Runtime checks that narrow a value to a more specific type.

Since TS 1.4 Spec ↗

Syntax

typeof / instanceof / in / x is T

Examples

function len(x: string | string[]) {
  if (typeof x === 'string') return x.length;
  return x.reduce((a, s) => a + s.length, 0);
}
function isError(e: unknown): e is Error {
  return e instanceof Error;
}

Notes

Built-in guards include `typeof`, `instanceof`, `in`, equality, and truthiness checks. User-defined guards return a `x is T` predicate; assertion functions use `asserts`. Discriminated unions narrow by checking a shared literal tag property.

See also