Sub topic 7
Intersection Types: A Value That Satisfies Several Types
Assume you know basic TypeScript syntax, type aliases, object types, and function annotations. This chapter uses those features to explain how the intersection operator (&) combines requirements.
Combining object types
An intersection type describes a value that must satisfy every type in the intersection. If A requires one property and B requires another, A & B requires both properties.
type Named = {
name: string;
};
type Timestamped = {
createdAt: Date;
};
type Article = Named & Timestamped;
const post: Article = {
name: "Unions and intersections",
createdAt: new Date(),
};
function summarize(article: Article): string {
return `${article.name} was created at ${article.createdAt.toISOString()}`;
}
console.log(summarize(post));Article has the properties from Named and Timestamped. The object assigned to post must include both name and createdAt.
An intersection does not create a new runtime object. It only describes the requirements that TypeScript checks at compile time.
| Type expression | Required value |
|---|---|
| `Named` | `name` |
| `Timestamped` | `createdAt` |
| `Named & Timestamped` | `name` and `createdAt` |
You can intersect more than two types:
type Identified = {
id: number;
};
type Owned = {
owner: string;
};
type Versioned = {
version: number;
};
type Document = Identified & Owned & Versioned;
const document: Document = {
id: 7,
owner: "Mina",
version: 3,
};The value must meet all three contracts.
Intersection versus union
A union uses | to describe alternatives. An intersection uses & to combine requirements.
type Guest = {
name: string;
};
type Admin = {
permissions: string[];
};
type GuestOrAdmin = Guest | Admin;
type GuestAndAdmin = Guest & Admin;
const either: GuestOrAdmin = { name: "Ravi" };
const both: GuestAndAdmin = {
name: "Ravi",
permissions: ["edit-users"],
};GuestOrAdmin can contain the members of either type. GuestAndAdmin must contain the members of both types.
For a union, you can safely access only members shared by every possible member. For an intersection, TypeScript knows that every required member is present.
Reusing and extending contracts
Intersections are useful when several parts of an application contribute requirements to one value. For example, a database layer might add an identifier while an audit layer adds timestamps.
type UserInput = {
displayName: string;
email: string;
};
type DatabaseFields = {
id: number;
};
type AuditFields = {
createdAt: Date;
updatedAt: Date;
};
type StoredUser = UserInput & DatabaseFields & AuditFields;
function createStoredUser(input: UserInput): StoredUser {
const now = new Date();
return {
...input,
id: 1,
createdAt: now,
updatedAt: now,
};
}
console.log(createStoredUser({
displayName: "Ada",
email: "[email protected]",
}));The spread syntax copies the input properties into the returned object. The intersection type then requires the generated database and audit properties as well.
Visual model
Common mistakes
An intersection does not mean that a value may choose one side. This is incorrect because name alone does not satisfy Guest & Admin.
type Guest = { name: string };
type Admin = { permissions: string[] };
const invalid: Guest & Admin = {
name: "Ravi",
// Error: permissions is missing
};Also, intersections do not automatically remove optional properties. If a property is optional in both source types, it remains optional:
type HasLabel = {
label?: string;
};
type HasColor = {
color?: string;
};
type OptionalMetadata = HasLabel & HasColor;
const metadata: OptionalMetadata = {};The object can omit both properties because neither type requires them.
Exercise
What properties must an object assigned to type Report = { title: string } & { pageCount: number } contain?
Show answer
It must contain both title, with type string, and pageCount, with type number.