Intersection types in TypeScript

The basics of intersection types in TypeScript

T ypeScript allows us to combine multiple types into a single type using intersection types. This allows you to create a new type that contains all the properties of the original types.

Creating an intersection type

Imagine you want to create a holiday package type that consists of a car, flight, and hotel.

You can use intersection types for this, combining all properties from each type into a single, unified type.

The ampersand (&) symbol is used to combine types.

type Car = {
  brand: string;
  color: string;
};
 
type Flight = {
  from: string;
  to: string;
};
 
type Hotel = {
  name: string;
  address: string;
};
 
type HolidayPackage = Car & Flight & Hotel;

Things to watch out for

If you are intersecting two or more object types and there are duplicate keys that represent conflicting types (like in the example), the resulting key’s type will return type never.

type Flight = {
  id: string;
  from: string;
  to: string;
};
 
type Hotel = {
  id: number;
  name: string;
  address: string;
};
 
type HotelAndFlightPackage = Flight & Hotel;
 
const hotelAndFlightPackage: HotelAndFlightPackage = {
  id: "1", // ❌ TypeScript will expect type `never`
  from: "London",
  to: "Paris",
  name: "Hilton",
  address: "123 Main St",
};