Extending interfaces and intersection types

Intermediate · 5 min

Building bigger types from smaller ones with `interface extends` and the `&` operator, how each handles conflicts, and why `extends` is cheaper.

Before thisType aliases vs interfacesUnion and literal types

Andrew Burgess · 5 min

Extending interfaces and intersection types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Andrew BurgessReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `interface B extends A` copies every member of `A` into `B`; an interface can extend several interfaces at once, and also object-type aliases.
  • An extending interface may redeclare an inherited property with a narrower type, but an incompatible type is an error on the interface itself.
  • `A & B` describes values that satisfy both `A` and `B` at once, so it has the members of both; more requirements means fewer values qualify.
  • When the two sides of an intersection disagree about a property, there's no error at the declaration: the property becomes `never`, and if the clash is between literal types, the whole intersection collapses to `never`.
  • The compiler flattens an `extends` chain into a single cached object type, while intersections are recombined and rechecked where they're used, so the TypeScript team recommends `extends` for large or heavily used types.
  • Intersections remain the tool for combining things an interface can't extend, such as unions, function types, or generic type parameters.

The problem: shapes that share a core

Real data models repeat themselves. Customers, orders and invoices all have an id and a createdAt. Writing those fields into every type means they drift apart the first time someone renames one. What you want is to define the shared part once and build on it.

TypeScript gives you two tools for that. Interfaces have extends. Any type can use the intersection operator &. They look interchangeable for the simple cases, but they disagree sharply about what happens when the pieces conflict.

interface extends

interface Entity {
  id: string | number;
  createdAt: Date;
}

interface Timestamped {
  updatedAt: Date;
}

interface Order extends Entity, Timestamped {
  total: number;
}

Order now has id, createdAt, updatedAt and total. An interface can extend any number of other interfaces, and it can also extend an object-type alias:

type Animal = { name: string };

interface Pet extends Animal {
  owner: string;
}

You’re allowed to redeclare an inherited property, as long as the new type is assignable to the old one. Narrowing id to just string is fine, because a Customer is still a valid Entity:

interface Customer extends Entity {
  id: string; // fine: string fits in string | number
  email: string;
}

interface Broken extends Entity {
  id: boolean;
}
// Error: Interface 'Broken' incorrectly extends interface 'Entity'.
//   Types of property 'id' are incompatible.
//     Type 'boolean' is not assignable to type 'string | number'.

The error lands on the declaration, the moment you write the mistake. That’s the main thing extends buys you.

Intersection types with &

An intersection says “a value of this type must satisfy both sides”:

type WithId = { id: string };
type WithTimestamps = { createdAt: Date; updatedAt: Date };

type Tracked = WithId & WithTimestamps;
// { id: string; createdAt: Date; updatedAt: Date }

The name is confusing at first, because the result has more properties than either side, which sounds like a union. The set view clears it up. A type is a set of values. WithId is the set of all objects with a string id. WithTimestamps is the set of all objects with two dates. The values that are in both sets, the intersection, are the objects with all three properties. More conditions, fewer values that qualify.

Intersections work on any types, not just object shapes. That’s why they’re still needed even if you prefer interfaces: you can intersect a union, a function type, or a generic parameter T, none of which an interface can extend.

What happens on conflict

Here’s where the two tools part ways. Intersect two types that disagree about a property and nothing complains at the declaration:

type X = { id: string } & { id: number };
type XId = X["id"]; // never

const x: X = { id: "a" };
// Error: Type 'string' is not assignable to type 'never'.

No value is both a string and a number, so id becomes never, and the type is impossible to build. You find out only at the point where someone tries to create one, which may be far from the line that caused it.

When the clash is between two different literal types, as with the tag of a discriminated union, TypeScript goes further and reduces the whole intersection to never:

type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };

type Both = Circle & Square; // never

Compare that with extends, which refused the conflicting declaration outright. Same intent, very different feedback.

The performance note

The TypeScript team’s performance guide recommends extends over intersections for object types. An interface built with extends is flattened into one object type when it’s declared. The compiler caches it and can relate it to other types by name. An intersection is recomputed from its parts: whenever it’s compared with another type, each member is checked, and the results are less likely to be cached. On a few small types you won’t notice. On a large codebase where a big intersection type is used in thousands of places, it shows up in editor responsiveness and build times. The flattened interface also prints as a single name in errors rather than as A & B & C.

A practical rule: use extends when you’re building object shapes on top of each other, and keep & for the cases only it can handle.

About the video

Andrew Burgess’s short video is about the mental model, not the syntax. He treats types as sets of values and uses that to explain why a union is “this or that” while an intersection is “this and that”, and why the intersection ends up with more properties. That model is exactly what makes the conflict behaviour above predictable: an impossible condition gives an empty set, which is never. The video doesn’t cover interface extends, conflict errors or performance, which is why this lesson spends most of its time there.

Check yourself

  1. 01`interface Base { id: string | number }` is extended by `interface Customer extends Base { id: string }`. Is that allowed, and what about `id: boolean`?

    `id: string` is allowed because `string` is assignable to `string | number`, so every `Customer` is still a valid `Base`. `id: boolean` is rejected with an error that the interface incorrectly extends `Base`, because a `Customer` would no longer be usable where a `Base` is expected.

  2. 02What is the type of `id` in `type X = { id: string } & { id: number }`, and when do you find out something is wrong?

    It is `never`, because no value is both a string and a number. The type alias itself compiles without complaint; you only find out when you try to create an `X` and every value you give `id` is rejected as not assignable to `never`.

  3. 03Why does `{ kind: "circle"; r: number } & { kind: "square"; side: number }` reduce to `never` as a whole, rather than just having a `never` property?

    Both `kind` properties are literal types, and two different literals have nothing in common. TypeScript treats a conflict between such discriminant-style literal properties as proof that no object could ever satisfy the intersection, so it simplifies the entire type to `never`.

  4. 04If `A & B` combines the properties of both types, why is it described as a narrower type than `A`?

    Think of a type as the set of values it accepts. Every extra required property is an extra condition a value must meet, and adding conditions shrinks the set. The values that are both `A` and `B` are a subset of the values that are just `A`, even though the type's description lists more properties.

  5. 05Why is `interface C extends A, B {}` generally preferred over `type C = A & B` for large object types?

    `extends` checks for conflicts up front and produces one flattened object type that the compiler caches and compares by identity. An intersection has to be recombined and its parts checked each time it's related to another type, which adds up in big codebases and can produce longer error messages.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark