TypeScript by Example: Unions
Combining multiple types with TypeScript union syntax through detailed code examples. Shows how to create flexible parameters using the pipe operator, implement type guards with typeof checks, and use string literal unions for restricting values to specific constants.
Code
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
padLeft("Hello", 4); // " Hello"
padLeft("Hello", ">>>"); // ">>>Hello"
// padLeft("Hello", true); // Error: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.
// Literal Types
type Easing = "ease-in" | "ease-out" | "ease-in-out";
function animate(dx: number, dy: number, easing: Easing) {
// ...
}
animate(0, 0, "ease-in");Explanation
Union types allow a value to be one of several types. We use the vertical bar | to separate each type. In the example, string | number means the value can be either a string OR a number.
When working with a union type, TypeScript will only allow you to access members that are common to all types in the union. To access members specific to one type, you need to use a "type guard" (like typeof check) to narrow down the type.
You can also combine string literals into unions to create "String Literal Types". This is very useful for APIs that only accept a specific set of string values, acting like an enum but with string values.
Code Breakdown
padding: string | number allows either type for this parameter.typeof padding === "number" is a type guard for narrowing.type Easing creates a string literal union type.easing: Easing restricts the parameter to specific string values.
