Lesson 12 / 26
Union & Intersection Types
Combine types with OR (union) or AND (intersection).
Union types
| means "this value can be one of several types" — very common for IDs and API results.
function printId(id: string | number) {
console.log(`ID: ${id}`);
}
printId(101);
printId("abc-101");
printId(true);
// Error: Argument of type 'boolean' is not assignable...Intersection types
& merges multiple types into one that must satisfy all of them at once.
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
const p: Person = { name: "Ada", age: 36 }; // must have bothOR vs AND
Union (|) narrows what's allowed — any one of the listed types. Intersection (&) widens what's required — every property from every type.