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?"
Practice
let value: string | number;Solution
Step 1: Understand union type declaration
The syntaxstring | numbermeans the variable can hold either a string or a number.Step 2: Identify the purpose of union types
This flexibility allows one variable to store multiple types safely without errors.Final Answer:
To allow a variable to hold more than one type of value -> Option BQuick Check:
Union types = multiple allowed types [OK]
- Thinking union types make variables immutable
- Believing union types force a single type only
- Confusing union types with automatic type conversion
string or number in TypeScript?Solution
Step 1: Recall union type syntax
Union types use the pipe symbol|to separate types.Step 2: Compare options
let data: string | number; uses|correctly, while others use invalid syntax.Final Answer:
let data: string | number; -> Option CQuick Check:
Union syntax uses | symbol [OK]
- Using & instead of | for union types
- Separating types with commas
- Writing 'or' instead of |
function format(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase();
} else {
return value.toFixed(2);
}
}
console.log(format('hello'));
console.log(format(3.14159));Solution
Step 1: Analyze function behavior for string input
If input is a string,toUpperCase()converts it to uppercase, so 'hello' becomes 'HELLO'.Step 2: Analyze function behavior for number input
If input is a number,toFixed(2)formats it to 2 decimal places, so 3.14159 becomes '3.14'.Final Answer:
"HELLO" and "3.14" -> Option DQuick Check:
String upper + number fixed decimals = output [OK]
- Assuming no type check needed and causing errors
- Expecting original number without formatting
- Confusing toFixed output as number instead of string
function printLength(value: string | number) {
console.log(value.length);
}
printLength('test');
printLength(123);Solution
Step 1: Understand property access on union types
Accessinglengthonvalueis unsafe because numbers don't have alengthproperty.Step 2: Identify the error cause
TypeScript will raise an error to prevent runtime failure whenvalueis a number.Final Answer:
Error because number type has no 'length' property -> Option AQuick Check:
Accessing length on number causes error [OK]
- Ignoring type checks and expecting no error
- Thinking string has no length property
- Believing union types disallow functions
string or an Array<string> and returns the total number of characters. Which is the best way to use union types to achieve this?Solution
Step 1: Understand input types and their length
A string has a length property; an array of strings also has length, but we want total characters, so we join the array first.Step 2: Check union type handling
function countChars(input: string | string[]) { if (typeof input === 'string') { return input.length; } else { return input.join('').length; } } uses a type check to handle string and array separately, joining array elements to count total characters correctly.Final Answer:
function countChars(input: string | string[]) { if (typeof input === 'string') { return input.length; } else { return input.join('').length; } } -> Option AQuick Check:
Use type check and join array for total chars [OK]
- Using intersection (&) instead of union (|)
- Not checking type before accessing properties
- Using any type losing type safety
Ready to prove it?
Pass the test and this pattern moves unknown
