Intersecting Object Types
You'll learn how intersection types combine object shapes to form a single type with all properties from both.
What Does Intersecting Objects Mean?
When you intersect two object types using the & operator, TypeScript merges their properties into one combined type. Think of it like overlaying two transparencies — you see through to everything on both layers.
If you have an object with { name: string } and intersect it with { age: number }, the result is a single object type that requires both properties: { name: string; age: number }.
How Object Intersection Works
type Person = { name: string };
type Age = { age: number };
type PersonWithAge = Person & Age;
// PersonWithAge is now: { name: string; age: number }
const user: PersonWithAge = {
name: "Alice",
age: 30
};
Both properties are now required. You can't create a PersonWithAge without providing both name and age.
Practical Use Cases
This pattern shines when building up complex types from smaller pieces:
type Contact = { email: string };
type Address = { city: string };
type Employee = { id: number };
type FullEmployee = Contact & Address & Employee;
const employee: FullEmployee = {
email: "alice@example.com",
city: "Seattle",
id: 42
};
Each piece stays focused on one concern, but you can combine them as needed.
What About Property Conflicts?
If both types have the same property name, TypeScript intersects those property types too. We'll explore that complexity later, but for now, focus on combining distinct properties.
Key Takeaway: Intersecting object types with & merges their properties into one type that requires all properties from both sides.