Bird
Raised Fist0
Typescriptprogramming~10 mins

Exhaustive pattern matching in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Exhaustive pattern matching
Start with a value
↓
Match against patterns
↓
Check each pattern
↓
Handle
↓
All cases covered?
Yes↓
Return matched result
↓
End
The program checks a value against all possible patterns. If all patterns are covered, it returns the matched result. If any pattern is missing, it raises an error.
Execution Sample
Typescript
type Shape = { kind: 'circle', radius: number } | { kind: 'square', size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle': return Math.PI * shape.radius ** 2;
    case 'square': return shape.size ** 2;
  }
}
Calculates area for a shape by matching its kind, covering all possible shape types.
Execution Table
StepInput ValuePattern CheckedMatch ResultAction Taken
1{ kind: 'circle', radius: 3 }case 'circle'MatchCalculate area = π * 3^2 = 28.2743
2{ kind: 'circle', radius: 3 }case 'square'No MatchSkip
3All patterns checkedExhaustivenessAll coveredReturn result 28.2743
4{ kind: 'triangle', base: 4, height: 5 }case 'circle'No MatchSkip
5{ kind: 'triangle', base: 4, height: 5 }case 'square'No MatchSkip
6All patterns checkedExhaustivenessMissing patternError: Non-exhaustive patterns
💡 Execution stops when a matching pattern is found or an error occurs if patterns are not exhaustive.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6
shapeundefined{ kind: 'circle', radius: 3 }{ kind: 'circle', radius: 3 }{ kind: 'circle', radius: 3 }{ kind: 'triangle', base: 4, height: 5 }{ kind: 'triangle', base: 4, height: 5 }{ kind: 'triangle', base: 4, height: 5 }
matchedfalsetruefalsefalsefalsefalsefalse
resultundefined28.274328.274328.2743undefinedundefinederror
Key Moments - 2 Insights
Why does the program throw an error if a pattern is missing?
Because exhaustive pattern matching requires all possible cases to be handled. The execution_table rows 4-6 show that when 'triangle' is not matched by any case, the program detects missing patterns and raises an error.
What happens when the first pattern matches?
As shown in execution_table rows 1-3, once a matching pattern is found (case 'circle'), the program calculates the result and stops checking further patterns.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the 'matched' variable after step 2?
Afalse
Bundefined
Ctrue
Derror
💡 Hint
Check variable_tracker row 'matched' column 'After Step 2' to see if a pattern matched.
At which step does the program detect missing patterns and raise an error?
AStep 4
BStep 6
CStep 3
DStep 2
💡 Hint
Look at execution_table rows 4-6 where the input is a 'triangle' and no pattern matches.
If we add a case for 'triangle', how would the execution_table change for input { kind: 'triangle', base: 4, height: 5 }?
AIt would still raise an error at step 6.
BIt would skip all cases and return undefined.
CIt would match at step 4 and return a result without error.
DIt would match 'circle' case incorrectly.
💡 Hint
Adding a matching case prevents the missing pattern error shown in step 6.
Concept Snapshot
Exhaustive pattern matching checks a value against all possible cases.
All cases must be handled to avoid errors.
Use switch or match expressions with all variants.
If any case is missing, TypeScript signals an error.
This ensures safe and predictable code behavior.
Full Transcript
Exhaustive pattern matching means checking a value against every possible pattern it can have. In TypeScript, this is often done with a switch statement on a discriminated union type. The program tests each case one by one. If a case matches, it runs that code and stops checking further. If no cases match, and some patterns are missing, the program raises an error to warn the developer. This helps catch bugs early by ensuring all possible inputs are handled. The execution table shows how the program checks each pattern step-by-step, and the variable tracker shows how variables change during this process. Key moments clarify why missing patterns cause errors and how matching stops further checks. The visual quiz tests understanding of these steps. The quick snapshot summarizes the main points for easy recall.

Practice

(1/5)
1.

What is the main purpose of exhaustive pattern matching in TypeScript?

easy
A. To allow dynamic typing in TypeScript
B. To ensure all possible cases of a union type are handled
C. To improve runtime performance by skipping cases
D. To automatically generate switch cases

Solution

  1. Step 1: Understand union types and pattern matching

    Exhaustive pattern matching ensures every variant of a union type is explicitly handled in code.
  2. Step 2: Identify the purpose of exhaustive checks

    This prevents missing cases that could cause bugs or unexpected behavior.
  3. Final Answer:

    To ensure all possible cases of a union type are handled -> Option B
  4. Quick Check:

    Exhaustive pattern matching = handle all cases [OK]
Hint: Exhaustive means covering every case without missing any [OK]
Common Mistakes:
  • Thinking it improves runtime speed
  • Confusing with dynamic typing
  • Assuming it auto-generates code
2.

Which of the following switch statements correctly uses exhaustive pattern matching for this union type?

type Shape = 'circle' | 'square' | 'triangle';
easy
A. switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; }
B. switch(shape) { case 'circle': break; case 'square': break; default: break; }
C. switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; default: const _exhaustiveCheck: never = shape; }
D. switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; default: console.log('unknown'); }

Solution

  1. Step 1: Check all cases are handled

    Cases for 'circle', 'square', and 'triangle' are present in options B, C, and D.
  2. Step 2: Verify exhaustive check with never type

    Only switch(shape) { case 'circle': break; case 'square': break; case 'triangle': break; default: const _exhaustiveCheck: never = shape; } uses default with const _exhaustiveCheck: never = shape; to enforce exhaustiveness.
  3. Final Answer:

    switch with all cases and default assigning to never -> Option C
  4. Quick Check:

    Exhaustive switch = all cases + never default [OK]
Hint: Look for default assigning to never for exhaustiveness [OK]
Common Mistakes:
  • Omitting the default case with never assignment
  • Using default without never type
  • Missing one of the union cases
3.

What will be the output of this TypeScript code?

type Status = 'success' | 'error';
function handleStatus(status: Status) {
  switch (status) {
    case 'success':
      return 'Yay!';
    case 'error':
      return 'Oops!';
    default:
      const _exhaustiveCheck: never = status;
      return _exhaustiveCheck;
  }
}
console.log(handleStatus('success'));
medium
A. Compilation error
B. "Oops!"
C. Runtime error
D. "Yay!"

Solution

  1. Step 1: Analyze the switch cases for 'success'

    The input is 'success', so the first case matches and returns 'Yay!'.
  2. Step 2: Check the default case usage

    The default case is unreachable here but ensures exhaustiveness by assigning to never.
  3. Final Answer:

    "Yay!" -> Option D
  4. Quick Check:

    Input 'success' returns 'Yay!' [OK]
Hint: Match input case to return value directly [OK]
Common Mistakes:
  • Thinking default case runs for valid inputs
  • Expecting runtime or compile errors
  • Confusing return values for cases
4.

Identify the error in this exhaustive pattern matching code:

type Direction = 'up' | 'down' | 'left' | 'right';
function move(dir: Direction) {
  switch (dir) {
    case 'up':
      return 'Moving up';
    case 'down':
      return 'Moving down';
    case 'left':
      return 'Moving left';
    default:
      const _exhaustiveCheck: never = dir;
      return _exhaustiveCheck;
  }
}
medium
A. Missing case for 'right' in the switch statement
B. Default case should not assign to never
C. Function should return void instead of string
D. Switch statement syntax is incorrect

Solution

  1. Step 1: Check all union cases in switch

    Cases for 'up', 'down', and 'left' exist, but 'right' is missing.
  2. Step 2: Understand the role of default with never

    The default assigns to never to catch unhandled cases, so missing 'right' causes a compile error.
  3. Final Answer:

    Missing case for 'right' in the switch statement -> Option A
  4. Quick Check:

    All union cases must be handled explicitly [OK]
Hint: Check if all union members have cases before default [OK]
Common Mistakes:
  • Assuming default covers missing cases silently
  • Misusing never assignment in default
  • Ignoring missing union members
5.

Given this nested union type, which switch structure correctly uses exhaustive pattern matching to handle all cases?

type Animal = { type: 'dog'; breed: 'bulldog' | 'beagle' } | { type: 'cat'; color: 'black' | 'white' };
hard
A. switch(animal.type) { case 'dog': switch(animal.breed) { case 'bulldog': break; case 'beagle': break; default: const _exhaustiveCheck: never = animal.breed; } break; case 'cat': switch(animal.color) { case 'black': break; case 'white': break; default: const _exhaustiveCheck: never = animal.color; } break; default: const _exhaustiveCheck: never = animal.type; }
B. switch(animal.type) { case 'dog': if(animal.breed === 'bulldog' || animal.breed === 'beagle') break; break; case 'cat': if(animal.color === 'black' || animal.color === 'white') break; break; default: const _exhaustiveCheck: never = animal.type; }
C. switch(animal.type) { case 'dog': case 'cat': break; default: const _exhaustiveCheck: never = animal.type; }
D. switch(animal.type) { case 'dog': switch(animal.breed) { case 'bulldog': break; default: const _exhaustiveCheck: never = animal.breed; } break; case 'cat': switch(animal.color) { case 'black': break; case 'white': break; } break; default: const _exhaustiveCheck: never = animal.type; }

Solution

  1. Step 1: Check outer switch covers all 'type' cases

    Cases for 'dog' and 'cat' are present with default assigning to never.
  2. Step 2: Check inner switches cover all nested union cases

    For 'dog', both 'bulldog' and 'beagle' are handled with default never; for 'cat', both 'black' and 'white' are handled similarly.
  3. Step 3: Verify no missing cases in nested switches

    All nested union members are covered with exhaustive checks.
  4. Final Answer:

    Nested switches with all cases and never defaults for both levels -> Option A
  5. Quick Check:

    Nested exhaustive switches = all cases + never defaults [OK]
Hint: Use nested switches with never defaults for each union level [OK]
Common Mistakes:
  • Skipping some nested union cases
  • Using if conditions without exhaustive checks
  • Missing never assignment in inner switches
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard