How to use type narrowing in TypeScript

· Category: TypeScript

Short answer

Type narrowing is the process of refining a broader type to a more specific one through control flow analysis, equality checks, and specialized operators.

Steps

  1. Narrow with equality checks: if (status === 'loading') { ... }
  2. Narrow with truthiness: if (maybeString) { ... } removes null and undefined.
  3. Use the satisfies operator to check a value against a type without widening it.
  4. Narrow arrays with .filter() and custom type predicates.
  5. Use switch statements with discriminated unions for exhaustive narrowing.

Tips

  • TypeScript's control flow analysis works across function boundaries for closures in many cases.
  • The satisfies keyword is useful for config objects where you want autocomplete without losing literal types.

Common issues

  • Mutating a variable after narrowing can reset the type to the original broader type.
  • Narrowing any does not produce useful types; avoid any at the source.