How to work with intersection types in TypeScript



Image not found!!

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:

Creating Intersection Types:

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.

Intersection with Existing Types:

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, };

Combining Function Types:

You can use intersection types for function types as well:

typescript
type 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}!`); };

Limitations:

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.

typescript
type 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.