Intersection Types
Combining multiple types into a single, merged super-type.
The AND Operator for Types
While a Union (|) means 'one or the other', an Intersection (&) means 'both at the same time'.
When you intersect two object types, the resulting type is a single object containing all the properties from both original types.
Mixing and extending
Intersection types are incredibly useful for composition. Instead of writing massive, monolithic types, you can write small, focused types and combine them as needed.
For example, in React, you might combine native button props with your own custom props: type ButtonProps = React.ComponentProps<"button"> & { variant: 'primary' | 'secondary' };
Creating an Intersection
You define an intersection using the ampersand (&).
typescript
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age;
// Person is equivalent to: { name: string; age: number }
const p: Person = { name: "Alice", age: 30 };
Try it
Watch two separate types merge into a single, comprehensive super-type using the & operator.
name: string;
}
age: number;
}
name: string;
age: number;
}
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- An Intersection Type (
A & B) creates a type with all the properties of bothAandB. - They are excellent for composing small types into larger ones.
- Conflicting primitives in an intersection result in a
nevertype. - Prefer
interface extendsfor object composition when possible.
Done with this concept?
Mark it complete to track your progress. No login needed.