0
0
Typescriptprogramming~5 mins

Why union types are needed in Typescript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why union types are needed
O(n)
Understanding Time Complexity

We want to understand how using union types affects the time it takes for TypeScript code to run.

Specifically, we ask: How does the program's work grow when union types are involved?

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 = [1, 'hello', 3, 'world'];
inputs.forEach(v => console.log(processValue(v)));
    

This code processes an array of numbers and strings, handling each type differently using a union type.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping over the array with forEach and type checking each element.
  • How many times: Once for each element in the input array.
How Execution Grows With Input

As the input array grows, the number of times we check the type and process values grows directly with it.

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

Pattern observation: The work grows evenly as the input size grows; doubling input doubles work.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Using union types makes the program run slower exponentially because it checks many types."

[OK] Correct: Each item is checked once, so the time grows linearly, not exponentially.

Interview Connect

Understanding how union types affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if we added nested union types or arrays inside the union? How would the time complexity change?"