4 min read
•Question 5 of 48mediumWhat are Intersection Types in TypeScript?
Combining multiple types into one.
What You'll Learn
- What intersection types are
- How to combine types
- Use cases
Intersection Types
An intersection type combines multiple types into one using the & operator. The result has all properties from all types.
code.tsTypeScript
type Person = {
name: string;
age: number;
};
type Employee = {
employeeId: string;
department: string;
};
// Intersection: has all properties
type Staff = Person & Employee;
const staff: Staff = {
name: "John",
age: 30,
employeeId: "E123",
department: "Engineering"
};Extending Interfaces
code.tsTypeScript
interface Printable {
print(): void;
}
interface Loggable {
log(): void;
}
type Document = Printable & Loggable;
const doc: Document = {
print() { console.log("Printing..."); },
log() { console.log("Logging..."); }
};Use Cases
- Mixing in behaviors
- Combining configurations
- Creating complex object shapes