Intersection Types

Combine several types into one that has all their members.

Syntaxtype C = A & B;

An intersection type uses & to merge types. The result must satisfy all of them at once.

Where a union means "one or the other", an intersection means "both together". It is often used to combine object shapes.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A function merges two separate interfaces into one parameter using an intersection so the caller must supply all fields.
  • A mixin pattern extends a base object with additional logged metadata by intersecting the types.
  • An API response type combines Paginated & UserList to model a paginated collection of users.

More examples

Intersect two types

Creates a Person type that requires all fields from both Named and Aged by intersecting them.

Example · ts
type Named = { name: string };
type Aged = { age: number };

type Person = Named & Aged;

const alice: Person = { name: 'Alice', age: 30 };
// Both name and age are required

Intersection in a function

Requires a function argument to satisfy two separate interfaces at once using an intersection type.

Example · ts
interface Serializable {
  serialize(): string;
}

interface Loggable {
  log(): void;
}

function handle(obj: Serializable & Loggable): void {
  obj.log();
  console.log(obj.serialize());
}

Merging partial config objects

Combines two partial configuration shapes into a complete ServerConfig that requires all four fields.

Example · ts
type BaseConfig = { host: string; port: number };
type TLSConfig = { tls: boolean; cert: string };

type ServerConfig = BaseConfig & TLSConfig;

const server: ServerConfig = {
  host: 'localhost',
  port: 443,
  tls: true,
  cert: '/etc/ssl/cert.pem',
};

Discussion

  • Be the first to comment on this lesson.