Union types (A | B) represent values that can be one of several types - use when a value could be different types. Intersection types (A & B) combine multiple types into one - use when a value must satisfy all types simultaneously.
Union Types (|):
Intersection Types (&):
Type Narrowing:
// Union of primitives
type ID = string | number;
function printId(id: ID) {
// Can only access properties common to both types
console.log(id.toString()); // OK - both have toString()
// Must narrow before type-specific operations
if (typeof id === 'string') {
console.log(id.toUpperCase()); // OK - narrowed to string
} else {
console.log(id.toFixed(2)); // OK - narrowed to number
}
}
printId(123); // OK
printId('abc'); // OK
printId(true); // Error: boolean not assignable to ID
// Union of literal types (string literals)
type Direction = 'north' | 'south' | 'east' | 'west';
function move(direction: Direction) {
console.log(`Moving ${direction}`);
}
move('north'); // OK
move('up'); // Error: 'up' is not assignable to Direction