Model values that can be one of several types, and narrow them safely.
A union type says a value can be one of several types, separated by |:
let id: string | number;
id = "abc-123"; // ✓
id = 42; // ✓
id = true; // ❌ Error
This is useful when a function accepts or returns values of different shapes.
When you have a union, TypeScript needs help knowing which specific type you're working with. Use typeof or in checks:
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase(); // TypeScript knows id is string here
}
return id.toFixed(0); // TypeScript knows id is number here
}
You can also union specific string/number values to build an enum-like type:
type Direction = "north" | "south" | "east" | "west";
function move(dir: Direction) {
console.log("Moving", dir);
}
move("north"); // ✓
move("up"); // ❌ Error
Export a function formatValue that accepts a string | number and:
string: returns it in UPPERCASEnumber: returns it multiplied by 2Export a type alias Status that is a union of the string literals "active", "inactive", and "pending".
// 1. Export a function 'formatValue(val: string | number)': // - if string → return val.toUpperCase() // - if number → return val * 2 // // 2. Export a type alias 'Status' = "active" | "inactive" | "pending"