0
0
Typescriptprogramming~5 mins

Discriminated unions in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Discriminated unions
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows linearly (O(n)) with the number of shapes processed.

Final Time Complexity

Time Complexity: O(n)

This means checking the kind and calculating area takes time proportional to the number of shapes processed.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if the function had to check multiple properties or nested discriminated unions? How would the time complexity change?"