TypeScript Intersection Types
An intersection type combines multiple types into one, meaning the resulting type must satisfy all of the combined types at once. It is written using the `&` symbol between types.
Intersections are commonly used to merge multiple interfaces or object types together, which is helpful when you want to build a bigger type out of smaller reusable pieces.
type Combined = TypeA & TypeB;Combining types
Writing `TypeA & TypeB` creates a new type that requires all properties from both TypeA and TypeB. Any object of this type must satisfy every requirement.
Common use case
Intersections are often used to combine a base interface with extra properties, such as combining a `Person` type with an `Employee` type to create a full employee record.
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age;
const p: Person = { name: "Sam", age: 25 };
console.log(p);{ name: 'Sam', age: 25 }Person requires both a name and an age property because it intersects Name and Age.
type Employee = { id: number };
type Manager = { teamSize: number };
type TeamLead = Employee & Manager;
const lead: TeamLead = { id: 1, teamSize: 5 };
console.log(`Lead ${lead.id} manages ${lead.teamSize} people`);Lead 1 manages 5 peopleTeamLead must include all properties from both Employee and Manager.
Key points
- Intersection types are written using the `&` symbol.
- An intersection type requires all properties from every combined type.
- Intersections are useful for composing smaller types into bigger ones.
- They differ from unions, which allow only one of the listed types.
