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?"
Practice
Solution
Step 1: Understand union type purpose
A union type lets a variable accept values from multiple specified types, not just one.Step 2: Compare options with definition
Only Hold values of multiple specified types safely correctly describes this behavior; others describe fixed or automatic conversions which union types do not do.Final Answer:
Hold values of multiple specified types safely -> Option AQuick Check:
Union type = multiple types allowed [OK]
- Thinking union types convert values automatically
- Believing union types restrict to one type only
- Confusing union with intersection types
value that can be either a string or a number?Solution
Step 1: Recall union type syntax
Union types use the pipe symbol | between types without parentheses needed.Step 2: Evaluate each option
let value: string | number; uses correct syntax:string | number. let value: string & number; uses & which means intersection, not union. let value: string, number; uses comma which is invalid. let value: string | number[]; uses number[] which is an array of numbers, not a single number.Final Answer:
let value: string | number; -> Option AQuick Check:
Union syntax uses | without commas [OK]
- Using & instead of | for union types
- Separating types with commas
- Using number[] instead of number
function printId(id: string | number) {
if (typeof id === 'string') {
console.log('ID is a string: ' + id.toUpperCase());
} else {
console.log('ID is a number: ' + id.toFixed(2));
}
}
printId(42);Solution
Step 1: Analyze type check and method calls
The function checks ifidis a string or number. For number, it callstoFixed(2)which formats number with 2 decimals.Step 2: Apply input and output
Input is 42 (number), so else branch runs and prints 'ID is a number: 42.00'.Final Answer:
ID is a number: 42.00 -> Option CQuick Check:
Number uses toFixed(2) = 42.00 [OK]
- Calling string methods on numbers without check
- Expecting no decimal places in toFixed output
- Ignoring type narrowing with typeof
function formatInput(input: string | number) {
return input.toUpperCase();
}Solution
Step 1: Check method usage on union type
MethodtoUpperCase()exists on string but not on number.Step 2: Understand type safety with union
Without checking type, callingtoUpperCase()oninputcauses error because input might be number.Final Answer:
Error: toUpperCase() not available on number -> Option BQuick Check:
Call methods only after type check [OK]
- Calling string methods on union without type check
- Assuming union types allow all methods
- Ignoring compiler errors about method availability
type Result = string | null;
function process(value: Result) {
return value?.toUpperCase() ?? 'No value';
}
console.log(process(null));
console.log(process('hello'));Solution
Step 1: Understand optional chaining and nullish coalescing
The expressionvalue?.toUpperCase()callstoUpperCase()only ifvalueis not null or undefined. Otherwise, it returns undefined.Step 2: Apply nullish coalescing fallback
If the left side is undefined,?? 'No value'returns 'No value'. So fornull, output is 'No value'. For 'hello', it returns 'HELLO'.Final Answer:
No value HELLO -> Option DQuick Check:
Optional chaining + ?? handles null safely [OK]
- Expecting error when calling method on null
- Ignoring optional chaining usage
- Confusing null and undefined handling
Ready to prove it?
Pass the test and this pattern moves unknown
