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
- Narrow with equality checks:
if (status === 'loading') { ... } - Narrow with truthiness:
if (maybeString) { ... }removes null and undefined. - Use the
satisfiesoperator to check a value against a type without widening it. - Narrow arrays with
.filter()and custom type predicates. - Use
switchstatements with discriminated unions for exhaustive narrowing.
Tips
- TypeScript's control flow analysis works across function boundaries for closures in many cases.
- The
satisfieskeyword 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
anydoes not produce useful types; avoidanyat the source.