TypeScript
Intersection types
Learn intersection, combining multiple types.
What is an intersection type?
An intersection type combines multiple types into a single type. The types are separated by & (ampersand). The resulting type must have all the properties of every type.
interface HasName { name: string; }
interface HasAge { age: number; }
type Person = HasName & HasAge;
const p: Person = { name: "Ada", age: 30 };
An object of type Person must contain both name and age.
Combining types with intersection
Intersection is useful for combining small interfaces into a single type. Each interface is responsible for one set of properties; the resulting type carries all of them.
type Drivable = { drive(): void };
type Flyable = { fly(): void };
type FlyingCar = Drivable & Flyable;
const fc: FlyingCar = {
drive() {},
fly() {}
};
This makes it easy to compose types from small pieces.
Exercise Define a worker using intersection
Define an Employee interface with id: number. Define a Contact interface with email: string. Define the Worker type as Employee & Contact. The function describe(w: Worker): string should return w.id + "-" + w.email and print the result.
Show example solution
interface Employee { id: number; }
interface Contact { email: string; }
type Worker = Employee & Contact;
function describe(w: Worker): string {
return w.id + "-" + w.email;
}
const dev: Worker = { id: 1, email: "dev@x.com" };
console.log(describe(dev));
Test yourself
-
Which of the following can be assigned to a variable of type Person (HasName & HasAge)?
interface HasName { name: string; }
interface HasAge { age: number; }
type Person = HasName & HasAge;
const p: Person = ???
- { name: 'Ada' }
- {}
- { age: 30 }
- { name: 'Ada', age: 30 }
Show answer
{ name: 'Ada', age: 30 } — An intersection requires the properties of every type. HasName & HasAge needs both name and age.
-
Complete the intersection operator
type Person = HasName ____ HasAge;
Show answer
type Person = HasName & HasAge;
-
Intersection parts
- &
- Intersects types (and)
- A & B
- All properties of A and B
- Drivable & Flyable
- Both drivable and flyable
- HasName & HasAge
- Both name and age required
Next lesson: Literal types