Union type syntax and behavior in Typescript - Time & Space 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?
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.
- Primary operation: Looping through each element in the array and checking its type.
- How many times: Once for each element in the input array.
Each new item adds one more type check and one more operation based on that type.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks and 10 operations |
| 100 | About 100 type checks and 100 operations |
| 1000 | About 1000 type checks and 1000 operations |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to process values grows in a straight line with the number of items.
[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.
Understanding how union types affect performance helps you explain your code clearly and reason about efficiency in real projects.
"What if the array contained nested arrays of union types? How would the time complexity change?"