TypeScript Union and Intersection Types
Combining types with unions and intersections
Union Types
let value: string | number; # can be string OR number
value = 'hello';
value = 42;
Union with Literals
type Status = 'pending' | 'approved' | 'rejected'; # literal union
let status: Status = 'pending';
Type Guards
function process(value: string | number) {
if (typeof value === 'string') { # type guard
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
Intersection Types
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type Staff = Person & Employee; # combine types
let staff: Staff = {
name: 'John',
employeeId: 123
};