Sub topic 9
Intersections or interface extends
This chapter compares two ways to build a larger object type from smaller ones: the & intersection operator and interface ... extends. It assumes you know basic TypeScript syntax, type aliases, object types, and how union and intersection types work (covered in earlier chapters). You will learn where the two behave the same, where they differ, and how to choose between them.
Two ways to say the same thing
Both forms below describe an Article that has a name, a createdAt, and a title.
interface Named {
name: string;
}
interface Timestamped {
createdAt: Date;
}
interface ArticleInterface extends Named, Timestamped {
title: string;
}
type ArticleIntersection = Named & Timestamped & { title: string };
const a: ArticleInterface = { name: "Unions", createdAt: new Date(), title: "Intro" };
const b: ArticleIntersection = a;
const c: ArticleInterface = b;The last two lines show that the two types are mutually assignable. For ordinary object types, both forms produce the same set of accepted values. The differences are in what each form allows, how it reports problems, and how the compiler handles it.
Difference 1: conflicts are handled differently
When a derived interface redeclares a property, the compiler checks that the new type is assignable to the old one. A narrower type is accepted. An incompatible type is an error at the declaration.
interface Base {
id: string | number;
label: string;
}
interface Narrower extends Base {
id: string; // allowed: string is assignable to string | number
}
// interface Bad extends Base {
// id: boolean; // error: Interface 'Bad' incorrectly extends interface 'Base'
// }An intersection never complains at the declaration. It combines the property types with &, and an impossible combination silently produces never.
type Left = { id: string };
type Right = { id: number };
type Both = Left & Right;
declare const both: Both;
const n: never = both.id; // id is string & number, which is neverThe type Both is legal, but no real value can satisfy it. You find the problem when you try to create a value or use the property, often far from where the mistake was made.
Intersections of object types are reduced to never as a whole only when the conflicting property is a discriminant, meaning its type is a literal such as "a" or "b". For { kind: "a" } & { kind: "b" } the whole type becomes never. For { id: string } & { id: number } only the property becomes never.
Difference 2: what you can combine
An interface can extend only an object type, or an intersection of object types, whose members are known when the declaration is compiled. An intersection accepts any type on either side.
This matters in three common situations.
Unions. You cannot extend a union with an interface, but you can intersect with one. The intersection distributes over the union members.
type Result =
| { ok: true; value: number }
| { ok: false; error: string };
// interface Detailed extends Result { requestId: string }
// error: An interface can only extend an object type or intersection
// of object types with statically known members.
type Detailed = Result & { requestId: string };
function log(r: Detailed): string {
if (r.ok) {
return `${r.requestId}: ${r.value}`;
}
return `${r.requestId}: ${r.error}`;
}Detailed expands to two object types, each with a requestId. The ok tag still narrows the union, so r.value and r.error are available in the right branches.
Type parameters. A generic helper can add fields to whatever type it receives. An interface cannot extend a bare type parameter, because the compiler does not know its members.
type WithId<T> = T & { id: string };
interface User {
name: string;
}
const user: WithId<User> = { name: "Ada", id: "u1" };
// interface WithIdInterface<T> extends T { id: string }
// error: An interface can only extend an object type or intersection
// of object types with statically known members.Primitives. Branded types attach a phantom property to a primitive. Only an intersection can do this.
type UserId = string & { readonly __brand: "UserId" };
function asUserId(s: string): UserId {
return s as UserId;
}
const id = asUserId("u1");
console.log(id.toUpperCase()); // string methods still workA plain string is not assignable to UserId, so functions that take a UserId cannot be called with an arbitrary string by mistake.
Difference 3: declaration merging
Declaring an interface twice with the same name merges the two declarations into one type. A type alias cannot be declared twice.
interface Config {
host: string;
}
interface Config {
port: number;
}
const config: Config = { host: "localhost", port: 8080 };Library authors rely on this to let users add fields to a shared type, for example adding properties to a framework's request object. If you write type Config = ... twice, the compiler reports a duplicate identifier. If you want a type that other code may augment, use an interface. If you want a type that nobody can accidentally reopen, use a type alias.
Merging also means an interface can be changed from outside its own file. That is sometimes useful and sometimes a surprise, so choose it deliberately.
Difference 4: modifiers on shared properties
When both sides of an intersection declare the same property, the result follows rules that differ from extends.
- Property types are intersected:
string | numbercombined withstringgivesstring. - A property is optional only if it is optional in every constituent.
{ a?: string } & { a: string }gives a requireda. - A property is
readonlyonly if it isreadonlyin every constituent.
type ReadOnlyId = { readonly id: string };
type MutableId = { id: string };
declare const both: ReadOnlyId & MutableId;
both.id = "changed"; // allowed, because one constituent is writableWith interface extends, the derived declaration decides the modifiers. If you redeclare id without readonly, that is the declaration that applies. The rule for intersections is easy to forget, so check it whenever a readonly field comes from a helper type you did not write.
Difference 5: compiler cost and error messages
The compiler treats the two forms differently internally.
- An interface is a named type. The compiler resolves it once and caches the relationships between interfaces. When it prints an error, it uses the interface name.
- An intersection is built each time it is used. The compiler must flatten the members and compare them property by property. Long chains of intersections can slow down type checking in large projects, and error messages often show a long expanded type instead of a short name.
For a few small types, this difference is not noticeable. In a large codebase with deep hierarchies, or when error messages become unreadable, switching a chain of & over object types to named interfaces is a reasonable fix. The TypeScript team's performance guidance makes the same recommendation.
Choosing between them
The diagram summarizes the decision.
The same information in table form:
| Situation | Better choice | Reason |
|---|---|---|
| Named object shape that grows over time | `interface extends` | Early conflict errors, readable names, cached by the compiler |
| Type that outside code should be able to augment | `interface` | Declaration merging |
| Adding fields to a generic `T` | Intersection | An interface cannot extend a type parameter |
| Adding fields to a union | Intersection | Distributes over each member |
| Branding a primitive | Intersection | Interfaces cannot extend `string` or `number` |
| One-off combination used inline | Intersection | No need to name a new interface |
Common mistakes
- Assuming an intersection checks for conflicts. It does not. If two sources disagree on a property type, you get
neverfor that property and an error later, when you use it. - Expecting
extendsto accept any type. An interface cannot extend a union, a primitive, or a bare type parameter. - Forgetting that
readonlyis lost in intersections. One writable constituent makes the property writable. - Building long
&chains in a hot path of a large project. Replace them with interfaces if type checking slows down or errors become unreadable. - Mixing the two without a reason. A type alias for an intersection of interfaces works, and so does an interface extending an intersection alias of object types. Pick one style per area of the code so readers know what to expect.
Exercise
You have type Shape = { kind: "circle"; radius: number } | { kind: "square"; size: number }; and want every shape to also carry id: string. Can you write interface IdShape extends Shape { id: string }? If not, what should you write instead, and does kind still narrow the result?
Show answer
No. An interface cannot extend a union type, and the compiler reports that it can only extend an object type or an intersection of object types with statically known members. Write type IdShape = Shape & { id: string };. The intersection distributes over the union, giving one object type per member, each with an id. The kind property still discriminates, so switch (s.kind) narrows to the circle or square member as before.
Exercise
What are the types of a and b, and which line, if any, is an error?
type X = { n: number; tag?: "x" };
type Y = { n: number; tag: "x" };
declare const v: X & Y;
const a = v.tag;
const b: X = { n: 1, tag: undefined };
interface Z extends X { n: string }
Show answer
a is "x", because in an intersection a property is optional only when it is optional in every constituent, and Y makes it required. The line const b: X = { n: 1, tag: undefined } is valid unless exactOptionalPropertyTypes is enabled. The line interface Z extends X { n: string } is an error, because string is not assignable to number and an interface must stay compatible with what it extends.