Mixing Object Types with Intersections
What You'll Learn
You'll learn how to combine multiple object types using intersections to create a single type that contains all properties from each constituent type.
The Core Idea
Think of intersection types with objects like mixing ingredients in a recipe: when you combine flour, sugar, and eggs, you get a mixture that has all three ingredients. Similarly, when you intersect object types, you get a new type that has all the properties from each object type.
This is different from unions (which mean "this or that"). Intersections mean "this and that" — the resulting type must satisfy all parts simultaneously.
How It Works
When you use the & operator between object types, TypeScript merges their properties:
type Person = {
name: string;
age: number;
};
type Employee = {
employeeId: string;
department: string;
};
type EmployeePerson = Person & Employee;
const worker: EmployeePerson = {
name: "Alice",
age: 30,
employeeId: "E123",
department: "Engineering"
};
The EmployeePerson type now requires all four properties: name, age, employeeId, and department.
Practical Use Cases
This pattern shines when modeling entities that combine multiple concerns:
type Timestamped = {
createdAt: string;
updatedAt: string;
};
type User = {
username: string;
email: string;
};
type TrackedUser = User & Timestamped;
Now TrackedUser has username, email, and timestamp fields — perfect for database records.
Key Takeaway: Intersections combine object types by merging all their properties, creating a single type that requires every property from each constituent type.