0
0
Typescriptprogramming~5 mins

Union type syntax and behavior in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Union type syntax and behavior
O(n)
Understanding Time Complexity

We want to understand how the time to check or use union types changes as the input grows.

How does the program's work grow when handling values that can be one of many types?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processValue(value: number | string) {
  if (typeof value === 'number') {
    return value * 2;
  } else {
    return value.toUpperCase();
  }
}

const inputs: (number | string)[] = [1, 'a', 2, 'b', 3];
inputs.forEach(v => processValue(v));
    

This code processes an array of values that can be numbers or strings, handling each type differently.

Identify Repeating Operations
  • Primary operation: Looping through each element in the array and checking its type.
  • How many times: Once for each element in the input array.
How Execution Grows With Input

Each new item adds one more type check and one more operation based on that type.

Input Size (n)Approx. Operations
10About 10 type checks and 10 operations
100About 100 type checks and 100 operations
1000About 1000 type checks and 1000 operations

Pattern observation: The work grows directly with the number of items; doubling items doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to process values grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Checking union types adds extra loops or nested checks making it slower than linear."

[OK] Correct: Each value is checked once, so the work grows only with the number of items, not more.

Interview Connect

Understanding how union types affect performance helps you explain your code clearly and reason about efficiency in real projects.

Self-Check

"What if the array contained nested arrays of union types? How would the time complexity change?"