How to use intersection Operator (`&`) In Typescript
The intesection operator (`&`) combines multiple types into a single type that has all the properties of the intersected types. This method creates a new type that matches the properties of the input type `T` also all the properties of `T`
Syntax:
type ObjectWithMatchingProperties<T> = {
[K in keyof T]: T[K];
} & T;
Example: The below code example uses the intersection operator to generte required generic type.
type ObjectWithMatchingProperties<T> = {
[K in keyof T]: T[K];
} & T;
interface Company {
name: string;
est: number;
}
type MatchingProductObject =
ObjectWithMatchingProperties<Company>;
const cmpny: MatchingProductObject = {
name: "w3wiki",
est: 2009
};
console.log(cmpny.name, ", Established in year: ", cmpny.est);
Output:
w3wiki, Established in year: 2009
How to Define Generic Type for Matching Object Property Types in TypeScript ?
In Typescript, efficiently managing object property types is essential for type safety and code maintainability. Several techniques can be used to define generic types that match the properties of the objects as listed and explained below.
Table of Content
- Using Record Utility Type
- Using Mappped Types
- Using Partial utility type
- Using intersection Operator (`&`)