Intersection types are a powerful feature in TypeScript that allow you to combine multiple types into a single type. This concept is particularly useful when you need to create complex types that inherit properties and methods from multiple sources.
An intersection type is defined using the &
operator. It creates a new type that includes all the properties and methods of the combined types. This is different from Union Types, which represent a value that can be one of several types.
To create an intersection type, use the following syntax:
type IntersectionType = Type1 & Type2 & Type3;
Here's a simple example:
interface Printable {
print(): void;
}
interface Loggable {
log(): void;
}
type PrintableLoggable = Printable & Loggable;
function createDocument(): PrintableLoggable {
return {
print() { console.log("Printing..."); },
log() { console.log("Logging..."); }
};
}
In this example, PrintableLoggable
is an intersection type that combines the Printable
and Loggable
interfaces.
Intersection types are particularly useful in the following scenarios:
Let's look at a more advanced example using intersection types:
interface Person {
name: string;
age: number;
}
interface Employee {
jobTitle: string;
employeeId: number;
}
type EmployeePerson = Person & Employee;
const worker: EmployeePerson = {
name: "John Doe",
age: 30,
jobTitle: "Software Developer",
employeeId: 12345
};
console.log(worker.name); // "John Doe"
console.log(worker.jobTitle); // "Software Developer"
In this example, we've created an EmployeePerson
type that combines the properties of both Person
and Employee
.
Intersection types in TypeScript provide a powerful way to combine multiple types, enabling more precise and flexible type definitions. By mastering this concept, you can create more expressive and maintainable code in your TypeScript projects.
For more advanced type manipulations, consider exploring Conditional Types and Mapped Types in TypeScript.