Union types are a powerful feature in TypeScript that allow a variable to hold values of multiple types. They provide flexibility while maintaining type safety, making your code more robust and expressive.
A union type is a type formed from two or more other types, representing values that may be any one of those types. It's denoted using the pipe (|
) symbol between the types.
Here's the basic syntax for declaring a union type:
let variable: Type1 | Type2 | Type3;
Union types are particularly useful in scenarios where a value could be one of several types. For example:
let result: number | string;
result = 42; // Valid
result = "success"; // Also valid
result = true; // Error: Type 'boolean' is not assignable to type 'number | string'
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
printId(101); // Valid
printId("202"); // Also valid
printId(true); // Error: Argument of type 'boolean' is not assignable to parameter of type 'number | string'
When working with union types, TypeScript uses a technique called type narrowing to determine the specific type within a union. This is often done using type guards:
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return " ".repeat(padding) + value;
}
return padding + value;
}
To further enhance your understanding of TypeScript's type system, explore these related topics:
Union types are a cornerstone of TypeScript's type system, enabling developers to write more flexible and type-safe code. By mastering this concept, you'll be well-equipped to handle various scenarios in your TypeScript projects.