0
0
Typescriptprogramming~5 mins

Exhaustive checking with never in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Exhaustive checking with never
O(n)
Understanding Time Complexity

We want to see how the time needed grows when using exhaustive checks with the never type in TypeScript.

How does the program behave as the number of cases to check increases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    type Shape = 'circle' | 'square' | 'triangle';

    function area(shape: Shape, size: number): number {
      switch (shape) {
        case 'circle':
          return Math.PI * size * size;
        case 'square':
          return size * size;
        case 'triangle':
          return (Math.sqrt(3) / 4) * size * size;
        default:
          const _exhaustiveCheck: never = shape;
          return _exhaustiveCheck;
      }
    }
    

This code calculates area for different shapes and uses never to ensure all cases are handled.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The switch statement checks the shape once per call.
  • How many times: Exactly one check per function call; no loops or recursion.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
3 (shapes)Up to 3 checks per call
10 (hypothetical shapes)Up to 10 checks per call
100 (hypothetical shapes)Up to 100 checks per call

Pattern observation: The number of checks grows linearly with the number of shape cases.

Final Time Complexity

Time Complexity: O(n)

This means the time to check grows directly with the number of shape cases you have.

Common Mistake

[X] Wrong: "Using never makes the code run faster or skip checks."

[OK] Correct: The never type is only for compile-time checks. At runtime, the switch still checks each case one by one.

Interview Connect

Understanding how exhaustive checks affect runtime helps you write safer code and explain your reasoning clearly in interviews.

Self-Check

"What if we replaced the switch with a dictionary lookup? How would the time complexity change?"