Manuals / TypeScript / Chapter 4

B · Modeling · intermediate · Week 2 · Chapter 4 of 11

Unions, narrowing & discriminated unions

Union types model "A or B". Narrowing refines unions with typeof, instanceof, in, and truthiness checks. Discriminated unions add a shared literal field for exhaustive switch — the pattern for API states and UI machines.

Path progress
29%

Step 1 of 5

Basic unions

type Id = string | number. Functions accepting unions must handle all cases or narrow first.

Basic unionsDrag stickies · tap for tips
Study mapDrag stickies · tap for tipsKeep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Assert the UIdrag · tap →Retry wiselydrag · tap →Seed datadrag · tap →Close the loopdrag · tap →Keep it shortdrag · tap →Name the waitdrag · tap →Scope locatorsdrag · tap →Trace when stuckdrag · tap →One browser firstdrag · tap →Isolate statedrag · tap →Pathwise hackdrag · tap →Basic unionsdrag · tap →Try thisdrag · tap →Follow the dashed drag · tap →

Do this now

Write formatId(id: string | number): string handling both.

Was this step clear?
Chapter learning outcomes
  • Union types
  • Type narrowing
  • Discriminated unions
  • Exhaustiveness checking
  • never type

Clear these before you leave

Side quest

UI state machine

Type a modal flow: closed | confirming | submitting | success | error. One renderModal(state) with exhaustive switch.