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.

Javascript
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 (`&`)

Similar Reads

Using Record Utility Type

The record utility type in TypeScript creates an object type with keys of type string and values of specified type T. It is suitable in cases where the keys of the objects are arbitrary strings like dictionaries or maps....

Using Mappped Types

Mapped Types allows you to trasform the properties of one type into another type. This approach defines a generic type ObjectWithMatchingProperties that maps each properties in the input type T to itself. effectively preserving the original types....

Using Partial utility type

The Partial utility type in typescript contructs a type with all the properties provided type set to optional. This approach is useful where you want t o define an object type where all the properties may or may not be present....

Using intersection Operator (`&`)

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`...

Using Conditional Types

Conditional Types in TypeScript allow us to create types that depend on other types. We can use conditional types to conditionally select the properties of an object based on certain conditions....

Contact Us