Sub topic 8
Combining Types with Intersections
This chapter covers intersection types: how & builds a new type from several existing ones, how it compares with extends, and which errors appear when the combined types conflict. It assumes you can write basic type annotations, you know how interfaces and type aliases declare object shapes, and you can run tsc or read errors in your editor.
What an intersection is
An intersection type combines two or more types into one. A value of the combined type must satisfy every member. You write it with the & operator.
interface Named {
name: string;
}
interface Employee extends Named {
employeeId: number;
}
type Timestamps = { createdAt: Date; updatedAt: Date };
type EmployeeRecord = Employee & Timestamps;
const record: EmployeeRecord = {
name: "Grace",
employeeId: 7,
createdAt: new Date(),
updatedAt: new Date(),
};EmployeeRecord has name, employeeId, createdAt, and updatedAt. If you leave out any one of them, the compiler reports an error. The operands can be interfaces, type aliases, or inline object types. The result is always a type alias, because you are naming the combination with type.
Think of the set of values. A & B contains only the values that belong to both A and B. For object types, a value that has every property of A and every property of B is in both sets. This is why an intersection of objects has more properties than either operand, even though the set of values shrinks.
The block above is intentionally not used. The diagram follows.
Intersections and structural typing
TypeScript compares shapes, not names. An intersection is checked the same way. A value is assignable to A & B when it is assignable to A and also assignable to B.
type HasId = { id: number };
type HasLabel = { label: string };
function show(item: HasId & HasLabel): string {
return `${item.id}: ${item.label}`;
}
const source = { id: 1, label: "first", extra: true };
console.log(show(source)); // "1: first"The variable source has an extra property, extra. It is not a fresh object literal at the call site, so the excess property check does not apply, and the call compiles. If you pass an object literal with extra directly, the compiler reports an excess property error.
type HasId = { id: number };
type HasLabel = { label: string };
function show(item: HasId & HasLabel): string {
return `${item.id}: ${item.label}`;
}
// error: Object literal may only specify known properties,
// and 'extra' does not exist in type 'HasId & HasLabel'.
// show({ id: 1, label: "first", extra: true });Combining more than two types
You can chain & as many times as you need. The order does not change which properties exist.
type WithId = { id: number };
type WithName = { name: string };
type WithTags = { tags: string[] };
type Tagged = WithId & WithName & WithTags;
const item: Tagged = { id: 1, name: "report", tags: ["q1", "finance"] };A common use is a "mixin" style type, where you add a few cross-cutting fields to many base shapes without writing a new interface for each one.
type Audited = { createdBy: string; createdAt: Date };
type WithAudit<T> = T & Audited;
type Invoice = { number: string; total: number };
type AuditedInvoice = WithAudit<Invoice>;
const invoice: AuditedInvoice = {
number: "INV-001",
total: 120,
createdBy: "ada",
createdAt: new Date(),
};WithAudit<T> is a generic alias. It works with any T, so you write the audit fields once.
Intersection versus extends
Both extends and & build a bigger shape out of smaller ones. They look similar in the common case, and they differ in how they treat conflicts and how the compiler reports them.
interface Base {
id: number;
}
// Using extends
interface WithNameExt extends Base {
name: string;
}
// Using an intersection
type WithNameInt = Base & { name: string };
const a: WithNameExt = { id: 1, name: "a" };
const b: WithNameInt = { id: 2, name: "b" };| Aspect | `interface X extends Y` | `type X = Y & Z` |
|---|---|---|
| Can combine unions | No, an interface can extend only object types with statically known members | Yes, `&` accepts any type, including unions |
| Conflicting property types | Compile error at the declaration | No error at the declaration, the property type becomes the intersection of both types |
| Error location | Points at the interface that conflicts | Often appears later, when you use the value |
| Result is an interface | Yes, so it can be merged and extended further | No, it is a type alias |
| Cost for the compiler | Cached, relationships are checked once | Can be recomputed for each use, which matters in very large codebases |
The conflict row is the one that causes surprises, so it gets its own section.
Conflicting properties
When two operands declare the same property with different types, extends refuses, and & accepts.
interface A {
value: string;
}
// error: Interface 'B' incorrectly extends interface 'A'.
// Types of property 'value' are incompatible.
// interface B extends A {
// value: number;
// }With an intersection, the compiler does not complain at the declaration. It computes the property type as the intersection of both property types.
type A = { value: string };
type B = { value: number };
type C = A & B;
// C["value"] is string & number, which is never
declare const c: C;
// c.value has type neverThe type string & number has no possible values, so it reduces to never. The type C itself is not never in every TypeScript version, but you cannot build a value of it, because no value can have a value property that is both a string and a number. Code that tries to create one fails to compile.
type A = { value: string };
type B = { value: number };
type C = A & B;
// error: Type 'string' is not assignable to type 'never'.
// const c: C = { value: "x" };When the property types overlap instead of clashing, the intersection narrows to what both agree on.
type A = { kind: "circle" | "square" };
type B = { kind: "square" | "triangle" };
type C = A & B;
// C["kind"] is ("circle" | "square") & ("square" | "triangle"), which is "square"
const c: C = { kind: "square" };This narrowing is useful on purpose. You can use an intersection to restrict a property that a base type leaves wide.
Optional and readonly in intersections
Modifiers combine in a predictable way. A property is required if it is required in any operand. A property is readonly only if it is readonly in every operand that declares it.
type A = { id: number; note?: string };
type B = { readonly id: number; note: string };
type C = A & B;
declare const c: C;
c.note.toUpperCase(); // fine, note is required because B requires it
c.id = 5; // allowed, id is writable in ABecause id is writable in A, the intersection permits writes. This surprises people who expect readonly to win. If you need the property to stay read-only, make it read-only in every operand, or wrap the result in Readonly<...>.
Intersections with unions
Intersection distributes over union. (A | B) & C is the same as (A & C) | (B & C). This lets you attach shared fields to every member of a union.
type Success = { ok: true; value: string };
type Failure = { ok: false; error: Error };
type Result = Success | Failure;
type WithRequestId = Result & { requestId: string };
function log(r: WithRequestId): string {
return r.ok ? `${r.requestId}: ${r.value}` : `${r.requestId}: ${r.error.message}`;
}The discriminant ok still narrows r, and requestId is available in both branches. An interface cannot do this with extends, because an interface cannot extend a union.
Intersections of primitives and branding
Intersecting two different primitive types gives never. Intersecting a primitive with an object type is a known technique called branding. It makes two values that share a runtime type incompatible at compile time.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function userId(raw: string): UserId {
return raw as UserId;
}
function loadUser(id: UserId): void {
console.log("loading", id);
}
const u = userId("u-1");
loadUser(u);
// error: Argument of type 'string' is not assignable to parameter of type 'UserId'.
// loadUser("u-1");The __brand property never exists at runtime. It exists only in the type, so a plain string cannot be passed where a UserId is expected. The cast in userId is the single place where you vouch for the value.
Intersecting function types
An intersection of function types describes an overloaded function. A value must be callable in every way the operands describe.
type ToNumber = (input: string) => number;
type ToString = (input: number) => string;
type Converter = ToNumber & ToString;
const convert: Converter = ((input: string | number) =>
typeof input === "string" ? Number(input) : String(input)) as Converter;
const n = convert("42"); // number
const s = convert(42); // stringThe compiler tries the operands in order and picks the first call signature that matches. The assertion is needed because an arrow function does not infer an overloaded type on its own.
When to prefer which
- Use
extendswhen you model a hierarchy of object shapes and want conflicts reported at the declaration. - Use
&when you combine alias types, add fields to every member of a union, or compose with generics such asT & Audited. - Use
&for branding, where an object type is attached to a primitive. - Avoid long chains of intersections of large types in hot paths of a big codebase. Prefer a named interface with
extends, which the compiler caches.
Summary of rules
A & Brequires a value to satisfy bothAandB.- For object types, the result has the properties of both operands.
- Conflicting property types combine into an intersection, often
never, with no error at the declaration. - A property is required if any operand requires it, and readonly only if every operand marks it readonly.
&distributes over|.- Intersections can combine unions and primitives, and
extendson an interface cannot.
Exercise
Given type A = { id: number; label: string } and type B = { id: string; active: boolean }, what is the type of id in A & B, and can you create a value of type A & B? Why does interface C extends A { id: string } behave differently?
Show answer
The type of id in A & B is number & string, which reduces to never. You cannot create a value of A & B, because no value of id can be both a number and a string, so an object literal with an id is rejected. The intersection itself is accepted without an error at the declaration. interface C extends A { id: string } is rejected at the declaration, because string is not assignable to number, so the compiler reports that interface C incorrectly extends A.
Exercise
Write a generic alias WithRequestId<T> that adds a required requestId: string property to any type T. Then say whether it can be applied to a union such as Success | Failure, and what the result looks like.
Show answer
type WithRequestId<T> = T & { requestId: string };. It can be applied to a union, because intersection distributes over union. WithRequestId<Success | Failure> is equivalent to (Success & { requestId: string }) | (Failure & { requestId: string }), so each member keeps its own properties and its discriminant, and gains requestId.