Unions
What
Union types allow a variable to hold values of several different types. It represents an “either-or” relationship between types.
How
You define a union type by separating the possible types with the pipe symbol (|). TypeScript also provides “type narrowing” where conditional checks can refine the type within a block of code:
// userId can be a string OR a number
let userId: string | number;
userId = "user_42";
userId = 42;
function safeSquare(val: string | number): number {
if (typeof val === "string") {
// Within this block, val is narrowed to a string
return Math.pow(parseInt(val), 2);
}
// Outside the block, if it's a number, it stays a number
return val * val;
}
Why
Unions are useful when a value could legitimately take multiple forms (like an ID being either a numeric index or a UUID string). They provide flexibility without sacrificing the safety of static typing.
Summary
Unions combine multiple types into one, and type narrowing ensures you handle each possibility safely.