Bird
Raised Fist0
Typescriptprogramming~10 mins

Exhaustive checking with never in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Exhaustive checking with never
Start with union type
↓
Switch on union cases
↓
Handle each case explicitly
↓
Use 'never' for unhandled cases
↓
Compiler error if any case missed
↓
End
This flow shows how to check all cases of a union type using a switch, and use 'never' to catch missing cases at compile time.
Execution Sample
Typescript
type Shape = 'circle' | 'square';
function area(shape: Shape) {
  switch(shape) {
    case 'circle': return 3.14 * 1 * 1;
    case 'square': return 1 * 1;
    default: const _exhaustiveCheck: never = shape;
  }
}
This code calculates area for shapes and uses 'never' in default to ensure all cases are handled.
Execution Table
StepInput shapeSwitch case matchedActionResult / Error
1'circle'case 'circle'Calculate area as 3.14 * 1 * 13.14
2'square'case 'square'Calculate area as 1 * 11
3'triangle'defaultAssign shape to never variableType error: 'triangle' not assignable to never
💡 Execution stops because 'triangle' is not part of Shape union, causing compile-time error at default case.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
shapeundefined'circle''square''triangle'
_exhaustiveCheckundefinedN/AN/AError: type mismatch
Key Moments - 2 Insights
Why does assigning 'shape' to a variable of type 'never' cause an error in the default case?
Because 'never' means no value is allowed. If the default case runs, it means some case was missed. The compiler uses this to catch unhandled cases, as shown in execution_table row 3.
What happens if we add a new shape to the union but forget to handle it in the switch?
The default case will catch it by assigning to 'never', causing a compile-time error. This forces you to handle the new shape explicitly, as seen in execution_table row 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result when input shape is 'circle'?
AType error
B1
C3.14
Dundefined
💡 Hint
Check execution_table row 1 under 'Result / Error'
At which step does the compiler error occur due to an unhandled case?
AStep 3
BStep 1
CStep 2
DNo error
💡 Hint
See execution_table row 3 where default case triggers error
If we remove the default case, what happens when a new shape is added but not handled?
ACompiler error still occurs
BNo error, but runtime may be wrong
CCode runs correctly
DTypeScript warns but compiles
💡 Hint
Default case with 'never' enforces compile-time check; without it, missing cases are not caught (see key_moments)
Concept Snapshot
Exhaustive checking with 'never':
- Use a switch on union types
- Handle all cases explicitly
- Add a default case assigning to a 'never' variable
- Compiler errors if any case is missed
- Helps catch bugs early by ensuring all cases handled
Full Transcript
This example shows how to use TypeScript's 'never' type to ensure all cases of a union type are handled in a switch statement. The code defines a union type 'Shape' with 'circle' and 'square'. The function 'area' switches on the shape and returns the area for each case. The default case assigns the shape to a variable of type 'never'. Since 'never' means no value is possible, if the default case runs, the compiler throws an error. This helps catch missing cases at compile time. The execution table shows the steps for inputs 'circle', 'square', and an invalid 'triangle'. The variable tracker shows how 'shape' changes and how '_exhaustiveCheck' causes an error when assigned an unexpected value. Key moments clarify why 'never' causes errors and how it helps maintain code safety. The quiz tests understanding of results, error steps, and the role of the default case. The snapshot summarizes the pattern for quick reference.

Practice

(1/5)
1. What is the main purpose of using never in exhaustive checking in TypeScript?
easy
A. To declare a variable that can hold any value
B. To allow any type of value without restrictions
C. To ignore errors during compilation
D. To ensure all possible cases are handled in a switch or conditional

Solution

  1. Step 1: Understand the role of never in exhaustive checks

    never is used to represent values that should never occur, helping catch unhandled cases.
  2. Step 2: Connect never usage to exhaustive case handling

    By forcing a function to accept never, TypeScript ensures all cases are covered, or else a compile error occurs.
  3. Final Answer:

    To ensure all possible cases are handled in a switch or conditional -> Option D
  4. Quick Check:

    Exhaustive checking = catch all cases [OK]
Hint: Use never to catch missing cases in switch statements [OK]
Common Mistakes:
  • Thinking never allows any value
  • Using never to ignore errors
  • Confusing never with unknown type
2. Which of the following is the correct syntax for a helper function that uses never to enforce exhaustive checking?
easy
A. function assertNever(x: never): never { throw new Error('Unexpected value: ' + x); }
B. function assertNever(x: any): void { console.log(x); }
C. function assertNever(x: unknown): never { return x; }
D. function assertNever(x: never): void { return; }

Solution

  1. Step 1: Identify correct parameter and return types

    The helper function must accept a parameter of type never and return never because it throws an error.
  2. Step 2: Check function body matches expected behavior

    The function throws an error with the unexpected value, which is the standard pattern for exhaustive checks.
  3. Final Answer:

    function assertNever(x: never): never { throw new Error('Unexpected value: ' + x); } -> Option A
  4. Quick Check:

    Helper function with never param and throw = correct [OK]
Hint: Helper must take never and throw error to enforce checks [OK]
Common Mistakes:
  • Using any or unknown instead of never
  • Not throwing an error inside the function
  • Returning void instead of never
3. What will be the output of this TypeScript code?
type Shape = 'circle' | 'square';
function area(shape: Shape) {
  switch (shape) {
    case 'circle':
      return 3.14 * 2 * 2;
    // Missing case for 'square'
    default:
      return assertNever(shape);
  }
}

function assertNever(x: never): never {
  throw new Error('Unexpected shape: ' + x);
}

console.log(area('square'));
medium
A. Returns 12.56
B. Throws Error: Unexpected shape: square
C. Returns undefined
D. Compilation error due to missing case

Solution

  1. Step 1: Analyze switch cases and input

    The function handles 'circle' but not 'square', so at runtime, calling area('square') hits the default case.
  2. Step 2: Understand assertNever behavior at runtime

    The assertNever function throws an error with the unexpected shape, so the program throws a runtime error.
  3. Final Answer:

    Throws Error: Unexpected shape: square -> Option B
  4. Quick Check:

    Missing case causes runtime error when called [OK]
Hint: Missing case triggers runtime error when called [OK]
Common Mistakes:
  • Assuming missing case returns undefined
  • Thinking it returns a number for all inputs
  • Expecting compile error instead of runtime error
4. Identify the error in this TypeScript code using exhaustive checking:
type Direction = 'up' | 'down' | 'left';
function move(dir: Direction) {
  switch (dir) {
    case 'up':
      return 'Moving up';
    case 'down':
      return 'Moving down';
    default:
      return assertNever(dir);
  }
}

function assertNever(x: never): never {
  throw new Error('Unexpected direction: ' + x);
}
medium
A. Missing case for 'left' in switch statement
B. assertNever function has wrong parameter type
C. Switch statement should not have a default case
D. Function move should return void instead of string

Solution

  1. Step 1: Check all union cases in switch

    The type Direction has 'up', 'down', and 'left', but 'left' is missing in the switch.
  2. Step 2: Understand impact of missing case with assertNever

    Missing 'left' causes default to call assertNever with a string, which is not never, causing a compile error.
  3. Final Answer:

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

    All union cases must be handled [OK]
Hint: Check all union cases explicitly to avoid errors [OK]
Common Mistakes:
  • Ignoring missing union cases
  • Thinking default case covers all safely
  • Wrong assertNever parameter type
5. Given this code, how can you modify it to ensure exhaustive checking for all Status values?
type Status = 'success' | 'error' | 'loading';

function handleStatus(status: Status) {
  switch (status) {
    case 'success':
      return 'Done';
    case 'error':
      return 'Failed';
    // Missing 'loading' case
    default:
      return assertNever(status);
  }
}

function assertNever(x: never): never {
  throw new Error('Unexpected status: ' + x);
}
hard
A. Change the type Status to include only 'success' and 'error'
B. Remove the default case and rely on TypeScript errors
C. Add a case for 'loading' in the switch statement
D. Change assertNever parameter type to any

Solution

  1. Step 1: Identify missing union case in switch

    The 'loading' case is missing, so the switch is not exhaustive.
  2. Step 2: Add missing case to ensure all Status values are handled

    Adding case 'loading': with appropriate return ensures exhaustive checking and no runtime errors.
  3. Final Answer:

    Add a case for 'loading' in the switch statement -> Option C
  4. Quick Check:

    All union members must have cases [OK]
Hint: Add missing union cases to switch for full coverage [OK]
Common Mistakes:
  • Removing default case without adding missing cases
  • Changing type to avoid handling all cases
  • Using any instead of never in assertNever
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