Why union types are needed in Typescript - Performance Analysis
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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the array with
forEachand type checking each element. - How many times: Once for each element in the input array.
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 |
|---|---|
| 10 | About 10 type checks and processing steps |
| 100 | About 100 type checks and processing steps |
| 1000 | About 1000 type checks and processing steps |
Pattern observation: The work grows evenly as the input size grows; doubling input doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items we process.
[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.
Understanding how union types affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we added nested union types or arrays inside the union? How would the time complexity change?"