Union and intersection types give you the power to describe complex data relationships. Union types (`|`) let you say "this could be one of these types," while intersection types (`&`) let you combine multiple types into one. These are essential for building robust type systems that accurately reflect your application's data structures.
Union and Intersection Types
Use union types when a value can be one of several different types, like a user's status that could be "active", "inactive", or "pending". Intersection types come in handy when you need to combine multiple type requirements, like creating a User object that has both an ID and authentication properties.
// Union types
let status: "active" | "inactive" | "pending" = "active";
let id: string | number = "user123";
// Type narrowing with typeof
function processValue(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
} else {
return value * 2;
}
}
// Intersection types
interface BaseUser {
id: number;
name: string;
}
interface AdminUser {
permissions: string[];
role: "admin";
}
type FullUser = BaseUser & AdminUser;
const admin: FullUser = { id: 1, name: "Bob", permissions: ["read", "write"], role: "admin" };
Try it Yourself โ