Intersection Type Definition
Intersection types are defined using the & operator. If you have two object types, Type1 and Type2, you can use Type1 & Type2 to create a new type that includes all properties of both Type1 and Type2.
Example:
Suppose we have two object types, Car and Truck:
typescripttype Car = { wheels: number; drive: () => void; }; type Truck = { cargo: boolean; loadCargo: (weight: number) => void; };
Now, if we need a type that can both drive and carry cargo, we can define this new type using intersection types:
typescripttype CarTruck = Car & Truck; let vehicle: CarTruck = { wheels: 4, drive: function() { console.log("Driving..."); }, cargo: true, loadCargo: function(weight: number) { console.log("Loading " + weight + " kg of cargo..."); } }; // Using CarTruck type object vehicle.drive(); vehicle.loadCargo(1000);
In this example, the CarTruck type combines the wheels and drive properties from the Car type and the cargo and loadCargo properties from the Truck type. This allows the vehicle object to access all methods and properties of both original types.
Use Cases
Intersection types are very useful in scenarios where you need to combine multiple type features, such as in large projects where you might need to combine different models or interfaces based on varying business logic. By using intersection types, you can flexibly build types that meet multiple requirements without having to redefine numerous new types, resulting in cleaner and more maintainable code.