Discriminated unions in Typescript - Time & Space Complexity
We want to understand how the time it takes to check and use discriminated unions grows as the input changes.
Specifically, how does the program's work change when it looks at different union types?
Analyze the time complexity of the following code snippet.
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 * shape.size;
}
}
This code checks the kind of shape and calculates its area accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single switch-case check on the shape's kind.
- How many times: Exactly once per function call, no loops or recursion.
Since the function only checks one property once, the work stays the same no matter how many shapes we have.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows linearly (O(n)) with the number of shapes processed.
Time Complexity: O(n)
This means checking the kind and calculating area takes time proportional to the number of shapes processed.
[X] Wrong: "Checking the kind property takes longer if there are more union types."
[OK] Correct: The check is a simple property read and switch, which does not get slower with more types because it happens once per call.
Understanding how discriminated unions work helps you write clear and efficient code that is easy to reason about, a skill valued in many coding tasks.
"What if the function had to check multiple properties or nested discriminated unions? How would the time complexity change?"