Exhaustive checking with never in Typescript - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
switchstatement checks the shape once per call. - How many times: Exactly one check per function call; no loops or recursion.
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.
Time Complexity: O(n)
This means the time to check grows directly with the number of shape cases you have.
[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.
Understanding how exhaustive checks affect runtime helps you write safer code and explain your reasoning clearly in interviews.
"What if we replaced the switch with a dictionary lookup? How would the time complexity change?"