Sub topic 7
Intersection types: a value that satisfies several types
This chapter assumes you know basic TypeScript syntax, type aliases, object types, and function parameter and return types. You should also be comfortable with union types from the earlier chapters. Here you will learn how the & operator builds a type from several others, what you can do with the result, and which mistakes come up most often.
What an intersection type is
An intersection type combines two or more types with &. A value has the intersection type only if it satisfies every member type at the same time.
type Named = { name: string };
type Timestamped = { createdAt: Date };
type Article = Named & Timestamped;
const post: Article = { name: "Unions and intersections", createdAt: new Date() };post must have a name string and a createdAt date. If either property is missing, the compiler reports an error:
type Named = { name: string };
type Timestamped = { createdAt: Date };
type Article = Named & Timestamped;
// Error: Property 'createdAt' is missing in type '{ name: string; }'
// but required in type 'Timestamped'.
const draft: Article = { name: "Draft" };A union says "one of these". An intersection says "all of these".
| Operator | Reads as | Properties you can use without narrowing | Values that qualify | Column |
|---|---|---|---|---|
| `A \ | B` | a value of type A or of type B | only those present in both A and B | values of A, plus values of B |
| `A & B` | a value of type A and of type B | every property of A and every property of B | only values that satisfy both A and B |
More properties, fewer values
For object types, an intersection looks like it does the opposite of what the symbol suggests. Article has more properties than Named, yet & is the "intersection" operator.
Both statements are true because they describe different things. Think of each type as the set of all values that satisfy it. Named is every object with a name string, and Timestamped is every object with a createdAt date. The intersection is the set of values that sit in both sets. That set is smaller, because each value must carry both properties. Requiring more properties means fewer values qualify.
Using an intersection value
Every member of every part is available without narrowing. This differs from a union, where you can access only the members common to all alternatives.
type Named = { name: string };
type Timestamped = { createdAt: Date };
type Article = Named & Timestamped;
function summarize(article: Article): string {
return `${article.name} (${article.createdAt.getFullYear()})`;
}An Article is also assignable to each of its parts. You can pass it wherever a Named or a Timestamped is expected:
type Named = { name: string };
type Timestamped = { createdAt: Date };
type Article = Named & Timestamped;
function greet(item: Named): string {
return `Hello, ${item.name}`;
}
const post: Article = { name: "Intersections", createdAt: new Date() };
console.log(greet(post)); // an Article is a NamedThe reverse is not true. A plain Named does not carry createdAt, so it is not assignable to Article.
Combining more than two types
You can chain as many types as you like. The order of the members does not change which properties the result has.
type Named = { name: string };
type Timestamped = { createdAt: Date };
type Authored = { author: string };
type Post = Named & Timestamped & Authored;
const p: Post = {
name: "Intersections",
createdAt: new Date(),
author: "Ada",
};You can also write the parts inline, which is useful for a one-off shape:
type Named = { name: string };
type Tagged = Named & { tags: string[] };
const t: Tagged = { name: "Guide", tags: ["typescript", "types"] };A practical use: adding fields to an existing type
Intersections are common as return types of functions that extend an object with extra data. The function below keeps the original type T and adds a createdAt field.
type Timestamped = { createdAt: Date };
function withTimestamp<T extends object>(value: T): T & Timestamped {
return { ...value, createdAt: new Date() };
}
const user = withTimestamp({ name: "Ada", role: "admin" });
console.log(user.name); // string, from the original object
console.log(user.createdAt); // Date, from TimestampedThe compiler infers T as { name: string; role: string }. The result type is { name: string; role: string } & Timestamped, so the caller keeps full type information about the original object. The return type does not hide name and role, which a plain Timestamped return type would.
Intersections with primitive types: branded types
You can intersect a primitive type with an object type. The result is a value that is still a string at runtime, but that the compiler treats as a distinct type. This technique is called branding.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function toUserId(raw: string): UserId {
return raw as UserId;
}
function loadUser(id: UserId): string {
return `user:${id}`;
}
const uid = toUserId("u-42");
loadUser(uid); // ok
// loadUser("u-42"); // Error: Argument of type 'string' is not assignable to parameter of type 'UserId'.
// const oid: OrderId = uid; // Error: the brand "UserId" does not match "OrderId".UserId is assignable to string, because it is a string plus extra information. So you can still call string methods on it, such as uid.toUpperCase(). The __brand property never exists at runtime. It exists only so the compiler can tell the two ids apart.
The assertion raw as UserId is allowed because UserId is a subtype of string. It is also the place where you promise the compiler that the string is valid, so keep these conversions in one small function, ideally one that validates its input.
Rules that help you predict the result
A few identities let you predict what an intersection simplifies to:
| Expression | Result | Why |
|---|---|---|
| `T & T` | `T` | Repeating a requirement adds nothing. |
| `T & unknown` | `T` | Every value is an `unknown`, so it adds no restriction. |
| `T & any` | `any` | `any` takes over the whole expression. |
| `T & never` | `never` | No value is a `T` and also a `never`. |
type Named = { name: string };
type A = Named & Named; // Named
type B = Named & unknown; // Named
type C = Named & never; // neverThe same reasoning explains why two unrelated primitive types give never. No value is both a string and a number. The next chapter covers conflicts like this one in detail, including what happens when two object types give the same property different types.
When two members declare the same property with the same type, the property appears once in the result:
type WithId = { id: string; label: string };
type WithIdAndFlag = { id: string; active: boolean };
type Merged = WithId & WithIdAndFlag;
const m: Merged = { id: "a1", label: "First", active: true };Common errors
Treating & as "either". A frequent mistake is to write Cat & Dog when you mean "a cat or a dog". The intersection requires a value with the members of both, so a plain cat object no longer qualifies. Use Cat | Dog for alternatives.
Excess property checks on object literals. When you assign an object literal directly to an intersection type, the compiler checks that every property in the literal exists in at least one member. A misspelled property is reported:
type Named = { name: string };
type Timestamped = { createdAt: Date };
type Article = Named & Timestamped;
const bad: Article = {
name: "Draft",
createdAt: new Date(),
// Error: Object literal may only specify known properties,
// and 'titel' does not exist in type 'Article'.
titel: "typo",
};Reading hover text. Editors often show Named & Timestamped rather than the flattened object. This is expected. The compiler does not merge intersections into one object type for display. If a long chain becomes hard to read, give the combination its own alias, such as type Article = ..., and use that name in signatures.
Expecting intersection to be the same as extends. An intersection and an interface that extends another interface often describe the same shape, but they are not identical in how they report errors or treat conflicting members. A later chapter compares them and gives criteria for choosing.
Narrowing assumptions. Because all members are accessible, you do not need typeof or in checks to read properties of an intersection. Narrowing becomes relevant again only when an intersection contains a union, which a later chapter covers.
Quick reference
A & Brequires a value to satisfy bothAandB.- Every property from every member is available without narrowing.
- An intersection value can be passed anywhere one of its member types is expected.
- Intersections of object types have more properties but accept fewer values than each member alone.
T & unknownisT, andT & neverisnever.- Intersecting a primitive with an object type creates a branded type that exists only at compile time.
Exercise
Given type Named = { name: string } and type Timestamped = { createdAt: Date }, which of these assignments compile, and why? (1) const a: Named & Timestamped = { name: "x" }; (2) const b: Named = { name: "x", createdAt: new Date() } as Named & Timestamped; (3) const c: Named & Timestamped = b;
Show answer
Only (2) compiles. (1) fails because createdAt is missing, and an intersection requires every member's properties. In (2) the assertion produces a Named & Timestamped value, and that type is assignable to Named because it satisfies Named. (3) fails because b has the declared type Named, which has no createdAt property, so it is not assignable to the intersection.
Exercise
Write a function addId that takes any object and returns it with a numeric id property added. Give it a return type that keeps the original object's properties. Then call it with { title: "Hello" } and read both title and id from the result.
Show answer
type WithId = { id: number }; function addId<T extends object>(value: T, id: number): T & WithId { return { ...value, id }; } const item = addId({ title: "Hello" }, 1); console.log(item.title); // "Hello" console.log(item.id); // 1 The return type T & WithId keeps everything from T and adds id. A return type of only WithId would hide title.
Exercise
Why does type Impossible = string & number reduce to never, while type Branded = string & { readonly __brand: "X" } does not?
Show answer
No value is both a string and a number, so the set of values that satisfy both is empty, and the compiler reduces the type to never. A string can also carry an object type with a __brand property, because the object type only describes a property the compiler checks. The two requirements do not contradict each other, so the intersection is a usable type.