TypeScript ยท Chapter 13 of 44

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.

Syntax
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.

Example 1 (typescript)
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age;

const p: Person = { name: "Sam", age: 25 };
console.log(p);
Output
{ name: 'Sam', age: 25 }

Person requires both a name and an age property because it intersects Name and Age.

Example 2 (typescript)
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`);
Output
Lead 1 manages 5 people

TeamLead 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.
๐Ÿ’ก Note: Intersections combine requirements (AND), while unions offer alternatives (OR) โ€” don't confuse the two.

๐Ÿ“ Quick Quiz

1. Which symbol creates an intersection type?

2. What must an object of an intersection type satisfy?

3. How do intersections differ from unions?