Intersection types in TypeScript allow you to combine multiple types into one. This is useful when you want a value to have properties from multiple types. You can create intersection types using the &
operator. Here's how you can work with intersection types in TypeScript:
typescript// Define two types
type Person = {
name: string;
age: number;
};
type Employee = {
jobTitle: string;
salary: number;
};
// Create an intersection type
type PersonWithJob = Person & Employee;
// Example usage
const johnDoe: PersonWithJob = {
name: 'John Doe',
age: 30,
jobTitle: 'Software Developer',
salary: 80000,
};
In this example, PersonWithJob
is an intersection type combining properties from both Person
and Employee
.
You can also use intersection types on existing types:
typescript// Define types
type Car = {
brand: string;
model: string;
};
type ElectricCar = {
batteryCapacity: number;
};
// Create an intersection type by combining existing types
type ElectricCarDetails = Car & ElectricCar;
// Example usage
const teslaModelS: ElectricCarDetails = {
brand: 'Tesla',
model: 'Model S',
batteryCapacity: 75,
};
You can use intersection types for function types as well:
typescripttype GreetFunction = (name: string) => void;
type FarewellFunction = (name: string) => void;
// Intersection of function types
type GreetAndFarewell = GreetFunction & FarewellFunction;
// Example usage
const greetAndFarewell: GreetAndFarewell = (name) => {
console.log(`Hello, ${name}!`);
console.log(`Goodbye, ${name}!`);
};
Keep in mind that intersection types can become less useful if the types you're combining have overlapping property names. In such cases, you might need to carefully consider the resulting type.
typescripttype A = { x: number; y: number };
type B = { y: number; z: number };
// Error: Intersection results in a type with duplicate property 'y'
type C = A & B;
In this example, the resulting type C
would have a duplicate property 'y'
, which TypeScript will flag as an error.
Intersection types are powerful tools in TypeScript, allowing you to create complex types by combining existing ones.