What if you could write one function that safely handles many types without messy code?
Why union types are needed in Typescript - The Real Reasons
Imagine you are building a form where a user can enter either a phone number or an email address. Without union types, you have to create separate variables or functions for each input type, making your code bulky and confusing.
Manually handling multiple possible types means writing repetitive checks and separate code paths. This slows you down and increases the chance of mistakes, like forgetting to handle one type or mixing up data.
Union types let you declare a variable or function parameter that can accept multiple types in a clean, simple way. This means you write less code and handle all cases clearly and safely.
function process(input: string) { /* handle string only */ }
function processNumber(input: number) { /* handle number only */ }function process(input: string | number) { /* handle string or number */ }Union types enable flexible and safe code that can work with different kinds of data without extra complexity.
When building a chat app, a message might be text or an image URL. Using union types, you can handle both message types in one function easily.
Manual handling of multiple types is repetitive and error-prone.
Union types let you combine multiple types in one place.
This leads to cleaner, safer, and more flexible code.
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
