Intersection types
- TypeScript course
- Beginner
- Lesson 60/89
- 4 min
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.
Practice 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.
Starter code
// Employee arayüzünü tanımla: id: number
// Contact arayüzünü tanımla: email: string
// Worker = Employee & Contact
// describe(w: Worker): string döndürür, id ve email arasına tire koySample 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));Expected output
1-dev@x.com
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 } Correct answer
Explanation: An intersection requires the properties of every type. HasName & HasAge needs both name and age.
2 Complete the intersection operator
type Person = HasName ____ HasAge;
type Person = HasName & HasAge;
Explanation: An intersection combines types with the & operator. HasName & HasAge requires the properties of both types.
3 Intersection parts
| Term | Meaning |
|---|---|
& |
Intersects types (and) |
A & B |
All properties of A and B |
Drivable & Flyable |
Both drivable and flyable |
HasName & HasAge |
Both name and age required |