TypeScript, a statically typed superset of JavaScript, offers powerful features for robust and error-free coding. One such feature is Union Types. In this guide, we’ll explore TypeScript Union Types, complete with practical examples and hands-on exercises to deepen your understanding.
Table of Contents
- Introducing Union Types
- Type Narrowing with Union Types
- Union Types and Arrays
- Literal Types
- Exercise
- Conclusion
Introducing Union Types
Union Types in TypeScript allow a variable to hold values of multiple types. This gives us the flexibility to work with dynamic data in a statically typed language. Here’s the basic syntax for defining a union type:
let variableName: type1 | type2 | type3...;
Code language: JavaScript (javascript)
For example:
let id: number | string;
id = 101; // This is valid
id = 'AB-101'; // This is also valid
Code language: JavaScript (javascript)
Type Narrowing with Union Types
Type narrowing is a technique TypeScript uses to narrow down the type of a variable at a given point in the code. Using typeof
and instanceof
operators, or control flow analysis, TypeScript can accurately predict the type within a certain scope.
let value: number | string;
value = Math.random() < 0.5 ? 'Hello' : 101;
if (typeof value === 'string') {
// Inside this block TypeScript knows `value` is a string
console.log(value.toUpperCase()); // OK
} else {
// Here TypeScript knows `value` is a number
console.log(value.toFixed(2)); // OK
}
Code language: JavaScript (javascript)
Union Types and Arrays
You can use Union Types with arrays when an array might contain elements of different types:
let arr: (number | string)[] = [1, 'Hello', 2, 'World'];
Code language: JavaScript (javascript)
Literal Types
Literal Types, combined with Union Types, allow variables to hold a value that must be a specific literal:
type Status = 'idle' | 'running' | 'stopped';
let serverStatus: Status;
serverStatus = 'running'; // This is valid
Code language: JavaScript (javascript)
In this example, serverStatus
can only be assigned the string values ‘idle’, ‘running’, or ‘stopped’.
Exercise
Ready for a challenge? Here’s a practice exercise:
- Create a function,
processValue
, that accepts a parameter which could be a string, number, or boolean. - If the input is a string, make the function return the uppercased version of the string.
- If the input is a number, return the square of the number.
- If the input is a boolean, invert the value and return it.
This exercise will help you practice defining union types, using type narrowing, and handling different types in functions.
Solution
Here is a possible solution for the exercise:
function processValue(value: string | number | boolean) {
if (typeof value === 'string') {
return value.toUpperCase();
} else if (typeof value === 'number') {
return value * value;
} else if (typeof value === 'boolean') {
return !value;
}
}
console.log(processValue('Hello')); // Outputs: 'HELLO'
console.log(processValue(7)); // Outputs: 49
console.log(processValue(true)); // Outputs: false
Code language: JavaScript (javascript)
In this function, we use type narrowing with the typeof
operator to check the type of value
. Depending on its type, we process it differently. If value
is a string, we return the uppercased version. If it’s a number, we return its square, and if it’s a boolean, we return its inverse.
Conclusion
Mastering TypeScript Union Types helps manage dynamic data more efficiently and aids in writing more robust and error-free code. Remember, the best way to solidify your understanding is by writing code and solving problems.