Skip to content
TypeScript Essentials

Lesson 4 of 6 · 22 min

x
4/6

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

Type Narrowing & Discriminated Unions

Type narrowing is the process by which TypeScript reduces a broad union type to a specific, concrete variant based on conditional control flow checks. Narrowing occurs through typeof, instanceof, equality checks, and the in operator.

Discriminated unions (also called tagged unions) represent one of TypeScript's most powerful patterns for state modeling. A discriminated union consists of object variants that share a common literal discriminant property (e.g., kind: 'success' | 'error'). In a switch statement, checking the discriminant allows TypeScript to automatically narrow properties inside each branch.

Before
Ambiguous State Modeling with Loose Properties
1// ❌ Risky: invalid states like { loading: true, error: 'Failed', data: [...] } are possible2interface State {3  loading: boolean;4  error?: string;5  data?: string[];6}
After
Discriminated Union State Machine
1type State =2  | { status: 'idle' }3  | { status: 'loading' }4  | { status: 'success'; data: string[] }5  | { status: 'error'; message: string };6 7function render(state: State) {8  switch (state.status) {9    case 'success':10      return state.data.join(', '); // ✅ Narrowed automatically!11    case 'error':12      return state.message;13    default:14      return 'Please wait...';15  }16}

Exercise

Model an async payment state as a discriminated union (status: 'idle' | 'processing' | 'completed' | 'failed') and write a type-safe handler function.

Check your understanding

  • What makes a union type 'discriminated'?Show answer

    Answer

    A common literal property (the discriminant) present in every variant of the union that TypeScript checks to narrow types.
  • How does exhaustive checking with the never type work?Show answer

    Answer

    By assigning unhandled switch default cases to a variable typed as never, TypeScript raises compile errors if a new union variant is added without updating the switch.
Previous

Progress is saved in this browser.

Next Lesson