Mastering Union and Intersection Types in TypeScript: Quick Guide with Examples

Union Types: Use union types when a variable or parameter can hold values of multiple types. Syntax: typeA | typeB Example: let value: string | number; value = "hello"; // valid value = 42; // vali...

By · · 1 min read
Mastering Union and Intersection Types in TypeScript: Quick Guide with Examples

Source: DEV Community

Union Types: Use union types when a variable or parameter can hold values of multiple types. Syntax: typeA | typeB Example: let value: string | number; value = "hello"; // valid value = 42; // valid value = true; // invalid Intersection Types: Use intersection types to combine multiple types into one. The resulting type has all properties from each type. Syntax: typeA & typeB Example: type A = { a: number }; type B = { b: string }; let obj: A & B = { a: 1, b: "hello" }; Key Differences: Union (|): Accepts values that match any member type. Intersection (&): Requires values to satisfy all member types. Practical Example: Suppose you have user types: type Admin = { name: string; admin: true }; type User = { name: string; admin?: false }; type AnyUser = Admin | User; // Can be either Admin or User function greet(user: AnyUser) { console.log(`Hello, ${user.name}`); } When to Use Them: Use unions when data can be of different shapes. Use intersections to combine multiple require