0
0
Typescriptprogramming~5 mins

Discriminated union narrowing in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Discriminated union narrowing
O(n)
Understanding Time Complexity

We want to understand how the time it takes to check types in a discriminated union grows as the number of cases increases.

How does the program's work change when we add more options to the union?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    type Shape =
      | { kind: 'circle'; radius: number }
      | { kind: 'square'; size: number }
      | { kind: 'rectangle'; width: number; height: number };

    function area(shape: Shape): number {
      switch (shape.kind) {
        case 'circle':
          return Math.PI * shape.radius ** 2;
        case 'square':
          return shape.size ** 2;
        case 'rectangle':
          return shape.width * shape.height;
      }
    }
    

This code calculates the area of a shape by checking its kind and then using the right formula.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The switch statement checks the shape's kind against each case.
  • How many times: It compares once per call, but the number of cases grows with the union size.
How Execution Grows With Input

As we add more shape types, the switch must check more cases before finding a match.

Input Size (number of cases)Approx. Operations (checks)
3Up to 3 checks
10Up to 10 checks
100Up to 100 checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to find the right case grows in direct proportion to how many cases there are.

Common Mistake

[X] Wrong: "Checking a discriminated union is always constant time because it just looks at one property."

[OK] Correct: While the property access is constant, the switch or if-else must compare against each case, so more cases mean more checks.

Interview Connect

Understanding how type checks scale helps you explain your code's efficiency clearly and shows you think about how programs behave as they grow.

Self-Check

"What if we replaced the switch with a map from kind to function? How would the time complexity change?"