TypeScript Fundamentals

Union Types & Narrowing

A union means a value may be one of several types. Narrowing uses runtime checks and control flow to refine what TypeScript knows inside a branch.
  • A union requires handling the possibilities
  • Runtime checks drive narrowing
  • Truthiness narrows but can be too broad
  • Narrowing follows control flow
  • Assertions bypass narrowing
Narrow before use
function printId(id: string | number) {
  if (typeof id === "string") {
    return id.toUpperCase()
  }

  return id.toFixed(0)
}
After the string branch returns, TypeScript knows the remaining path is number.
Narrowing tools
CheckNarrows
typeof value === 'string'Primitive categories
value instanceof ErrorClass/constructor instances
'kind' in valueObjects with property
value.kind === 'success'Discriminated union variant
isUser(value)Custom type guard
assertUser(value)Assertion function
Sources
  • The TypeScript HandbookNarrowing
  • Effective TypeScript, 2nd EditionType design
  • TypeScript ReferenceControl flow analysis