Intersections

`A & B` — "Both A AND B"

Intersections

An intersection combines types — the result has every property from each. Useful for adding to a base shape.

3 min read Level 1/5 #typescript#intersection#types
What you'll learn
  • Author intersection types
  • Use them to extend external types
  • Recognize when union beats intersection

An intersection combines two types — the result has every property from each.

The Syntax

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

type Person = Named & Aged;
// equivalent to: { name: string; age: number }

const ada: Person = { name: "Ada", age: 36 };

& is the intersection operator.

Adding to a Library Type

A common use — add fields to a third-party type:

import type { Express } from "express";

type CustomReq = Express.Request & {
  user?: { id: string };
};

The combined type has everything Express.Request has, PLUS user.

Union of Intersections

type Result =
  | { ok: true; data: User }
  | { ok: false; error: string };

type CachedResult = Result & { cached: boolean };
// → { ok: true; data: User; cached: boolean }
//   | { ok: false; error: string; cached: boolean }

The intersection distributes over the union.

When Members Conflict

If two intersected types have the same key with incompatible types, the result is never:

type A = { x: number };
type B = { x: string };

type C = A & B;
// type of c.x is `never` — no value satisfies both

Surprising the first time. Avoid intersecting types that share keys with different types.

Intersection vs Interface Extension

type Admin1 = User & { permissions: string[] };

interface Admin2 extends User {
  permissions: string[];
}

Functionally similar. Use whichever style your codebase prefers. interface extends has slightly better error messages when things go wrong.

Up Next

A specific kind of type — literal types.

Literal Types →