Intersection types

Topic 4 of 4 in Modelling data7 min readIntermediateFree course

Overview

Unions say “either this or that”. Intersections say “this and that”: a value of type A & B must satisfy both types at once. For object types, that means it has all the properties of both. Intersections let you build big types from small, reusable pieces.

Intersection types combine shapes. User (id: string, name: string) & Timestamps (createdAt: Date, updatedAt: Date) gives User & Timestamps, with id, name, createdAt and updatedAt. type SavedUser = User & Timestamps; must have ALL the properties. type Bad = string & number; is never — no value is both. A union (A | B) accepts values of either type; an intersection (A & B) needs values that are both at once. For object types that means “all the properties” — like interface extends, but works with any type.

Combining object types

TypeScript
type User = { id: string; name: string };
type Timestamps = { createdAt: Date; updatedAt: Date };

type SavedUser = User & Timestamps;

const u: SavedUser = {
  id: "u1",
  name: "Asha",
  createdAt: new Date(),
  updatedAt: new Date(),
};

Leave anything out and TypeScript complains, just as for a single object type. Hovering over SavedUser shows User & Timestamps; the properties appear in completions as if they were declared together.

Building from pieces

Intersections encourage small, focused types that you combine as needed:

TypeScript
type Identified = { id: string };
type Timestamped = { createdAt: Date; updatedAt: Date };
type SoftDeletable = { deletedAt: Date | null };

type Product = Identified & Timestamped & { name: string; price: number };
type Comment = Identified & Timestamped & SoftDeletable & { text: string };

Change Timestamped once, and every type that includes it updates.

A common use is adding properties to a type you get from elsewhere — a library’s props, a database row, an API response:

TypeScript
type ButtonProps = React.ComponentProps<"button"> & { variant: "primary" | "ghost" };
type ApiUser = UserFromDb & { links: { self: string } };

Intersections in functions

Spreading objects together produces an intersection naturally:

TypeScript
function withTimestamps<T extends object>(value: T, now: Date): T & Timestamped {
  return { ...value, createdAt: now, updatedAt: now };
}

(The <T extends object> part is a generic, coming up in the next chapter.) Object.assign(a, b) is typed the same way.

Union vs intersection

The names can be confusing, because they describe sets of values, not sets of properties:

A | B (union) A & B (intersection)
Accepts values of A or B values that are A and B
You can use only what both have in common (until you narrow) everything from both
For object types fewer guaranteed properties more required properties

A union is a bigger set of values with fewer guarantees; an intersection is a smaller set of values with more guarantees.

When intersections become never

Some intersections can’t have any values:

TypeScript
type Impossible = string & number;   // never — nothing is both
type Weird = "a" & "b";              // never

With object types, a conflicting property becomes impossible:

TypeScript
type A = { id: number };
type B = { id: string };
type C = A & B;   // { id: never } — you can never create one

TypeScript doesn’t report an error when you declare C; you only find out when you try to create a value. Compare interface:

TypeScript
interface A { id: number }
interface B extends A { id: string }
// error TS2430: Interface 'B' incorrectly extends interface 'A'.
//   Types of property 'id' are incompatible.
//     Type 'string' is not assignable to type 'number'.

That’s the practical difference between the two: extends checks for conflicts up front; & silently produces never. For building object hierarchies, interface … extends gives clearer errors; for combining types ad hoc — including types that aren’t plain objects — use &.

Intersections with primitives: branded types

There’s one deliberate use of intersecting a primitive with an object: branding. It gives a plain string or number a distinct type, so you can’t mix up two IDs:

TypeScript
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };

function asUserId(id: string): UserId {
  return id as UserId;   // the brand exists only in the type system
}

function getUser(id: UserId) { … }

const orderId = "o-17" as OrderId;
getUser(orderId);
// error TS2345: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'.

At run time they’re ordinary strings; in the type system they can’t be confused. Use this sparingly, for values where a mix-up would be costly (IDs, currencies, validated emails).

Remember: & means “has everything from both”. Use it to compose object types from small pieces — and watch for conflicts, which quietly turn into never.

Exercise

Compose a blog post

Define small reusable pieces: Identified (id: string), Timestamped (createdAt and updatedAt, both Date) and Authored (author: { name: string }). Define Draft (title, body) and build Post as Draft & Identified & Timestamped & Authored. Write publish(draft: Draft, author: string, now: Date): Post (id = the title lower-cased with spaces replaced by -) and edit(post: Post, changes: Partial<Draft>, now: Date): Post that returns a new post with updated fields and updatedAt. Print the post’s id, title and whether updatedAt changed. Show with // @ts-expect-error that a Post without author is rejected, and that type Impossible = string & number can’t hold any value.

TypeScript
// Reusable pieces

// Draft and Post

// publish() and edit()

Summary

  • A & B is a type whose values have everything from A and everything from B.
  • Intersections compose object types from small reusable pieces, like Post = Draft & Identified & Timestamped.
  • A union (A | B) is “either”; an intersection (A & B) is “both at once”.
  • Intersections of incompatible types (string & number) or conflicting properties become never.
  • For object hierarchies, interface … extends reports conflicts more clearly; intersections work with any type.