Type narrowing

Type narrowing is the refinement of a broad type into a more precise type inside a branch of code, thanks to checks such as typeof, instanceof, in or an equality comparison. The compiler follows this control flow and then allows the operations specific to the narrowed type.

Example

function f(x: string | number) {
  if (typeof x === 'string') return x.toUpperCase();
  return x.toFixed(2);
}

Related concepts

The whole glossary