Intersection Types
In this page:
Basic Intersection Types
The & operator creates an intersection type by combining two or more types into one, such as A & B. The resulting type requires everything demanded by every type in the intersection at once, rather than allowing just one of them.
Example: Basic Intersection Types
type A = { a: string };
type B = { b: number };
type AB = A & B;
const value: AB = { a: "x", b: 1 };
console.log(value);
Combining Object Types
Intersection types shine when an object needs to combine properties from several separate, focused concepts, such as combining a Timestamped type with a Named type. Each source type stays small and independently reusable, while the intersection assembles the complete required shape.
Example: Combining Object Types
type Timestamped = { createdAt: string };
type Named = { name: string };
type Entry = Timestamped & Named;
const entry: Entry = { createdAt: "2024", name: "Log Entry" };
console.log(entry);
Intersection Types with Functions
Intersection types can combine an object's data structure with additional capabilities, such as intersecting a plain data shape with a type that adds specific methods. This is useful when an object must satisfy several related groups of requirements at once.
Example: Intersection Types with Functions
type Data = { value: number };
type Loggable = { log: () => void };
const item: Data & Loggable = {
value: 42,
log() { console.log(this.value); },
};
item.log();
Multiple Intersections
More than two types can be combined in a single intersection, and the resulting type requires every property demanded by every one of the participating types. This scales naturally as more shared concerns need to be layered onto a single type.
Example: Multiple Intersections
type A = { a: string };
type B = { b: string };
type C = { c: string };
type ABC = A & B & C;
const value: ABC = { a: "1", b: "2", c: "3" };
console.log(value);
Intersection vs Union
The key distinction to keep straight is that a union means a value can satisfy any one of several types, while an intersection means a value must satisfy all of the combined types simultaneously. Confusing the two is a common source of confusing type errors, so understanding this difference matters a lot when designing TypeScript data structures.
Example: Intersection vs Union
type Union = string | number; // satisfies ANY one type
type Combo = { a: string } & { b: number }; // satisfies ALL types
let u: Union = 5;
let c: Combo = { a: "x", b: 1 };
console.log(u, c);
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: