How to Define Generic Type for Matching Object Property Types in TypeScript ?
Last Updated :
31 Jul, 2024
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.
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.
Syntax:
type ObjectWithMatchingProperties<T> = Record<string, T>;
Example: The below code implements the Record utility type to define generic type of matching object properties.
JavaScript
type ObjectWithMatchingProperties<T> =
Record<string, T>;
interface Company {
name: string;
workForce: number;
}
type MatchingPersonObject =
ObjectWithMatchingProperties<string | number>;
const cmpny: MatchingPersonObject = {
name: "GeeksforGeeks",
workForce: 200
};
console.log("Company: ", cmpny.name);
console.log("Work Force: ", cmpny.workForce, "+");
Output:
Company: GeeksforGeeks
Work Force: 200+
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.
Syntax:
type ObjectWithMatchingProperties<T> = {
[K in keyof T]: T[K];
};
Example: The below code uses the mapped types to create generic typ of matching object properties in TypeScript.
JavaScript
type ObjectWithMatchingProperties<T> = {
[K in keyof T]: T[K];
};
interface Company {
name: string;
desc: string;
est: number;
workForce: number;
}
type MatchingCompanyObject =
ObjectWithMatchingProperties<Company>;
const cmpny: MatchingCompanyObject = {
name: "GeeksforGeeks",
desc: "A Computer Science Portal.",
est: 2009,
workForce: 200,
};
console.log(cmpny.name, ", ", cmpny.desc, "Establishe in: ", cmpny.est);
console.log("Work Force: ", cmpny.workForce, "+");
Output:
GeeksforGeeks, A Computer Science Portal. Establishe in: 2009
Work Force: 200+
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.
Syntax:
type ObjectWithMatchingProperties<T> = Partial<T>;
Example: The below code makes use of the partial utility type to define generic type of object properties.
JavaScript
type ObjectWithMatchingProperties<T> = Partial<T>;
interface Book {
name: string;
desc: string;
}
type MatchingBookObject =
ObjectWithMatchingProperties<Book>;
const book: MatchingBookObject = {
name: "GeeksforGeeks",
desc: "A Computer Science Portal."
};
console.log(book.name);
console.log(book.desc);
Output:
GeeksforGeeks
A Computer Science Portal.
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`
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: "GeeksforGeeks",
est: 2009
};
console.log(cmpny.name, ", Established in year: ", cmpny.est);
Output:
GeeksforGeeks, Established in year: 2009
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.
Syntax:
type ObjectWithMatchingProperties<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
Example: In this example, we define a generic type ObjectWithMatchingProperties that selects only the properties of type T which are of type string.
JavaScript
type ObjectWithMatchingProperties<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
interface Person {
name: string;
age: number;
email: string;
}
type MatchingStringProperties = ObjectWithMatchingProperties<Person>;
const person: MatchingStringProperties = {
name: "Nikunj",
email: "[email protected]"
};
console.log("Name:", person.name);
console.log("Email:", person.email);
Output:
"Name:", "Nikunj"
"Email:", "[email protected]"
Using keyof and in Keywords with Generics
The keyof keyword in TypeScript is used to create a type whose keys are the property names of another type. Combined with the in keyword, you can iterate over the keys of a type to create a new type. This method allows you to define a generic type that matches the keys and properties of the input type T.
Syntax:
type ObjectWithMatchingProperties<T> = {
[K in keyof T]: T[K];
};
Example: The below code uses the keyof and in keywords to define a generic type that matches the properties of the input type.
JavaScript
type ObjectWithMatchingProperties<T> = {
[K in keyof T]: T[K];
};
interface Car {
make: string;
model: string;
year: number;
owner: string;
}
type MatchingCarProperties = ObjectWithMatchingProperties<Car>;
const car: MatchingCarProperties = {
make: "Tesla",
model: "Model 3",
year: 2023,
owner: "Nikunj"
};
console.log("Make:", car.make);
console.log("Model:", car.model);
console.log("Year:", car.year);
console.log("Owner:", car.owner);
OutputMake: Tesla
Model: Model 3
Year: 2023
Owner: Nikunj
Similar Reads
How to Define Strongly Type Nested Object Keys with Generics in TypeScript ?
We will look into the effective use of generics in TypeScript to ensure type safety when working with nested objects. By employing generics, developers can establish strongly typed keys for nested objects, significantly reducing the likelihood of runtime errors and enhancing code maintainability. Ta
2 min read
How to Define a Generic Type for an Array in TypeScript ?
Generics in TypeScript are a way to write reusable code that can work with different types of data. When it comes to defining generic types for arrays. TypeScript provides flexible options to ensure type safety while allowing for flexibility in the types of elements stored in the array. Table of Con
3 min read
How to Create TypeScript Generic Function with Safe Type Matching ?
In TypeScript, generic functions offer a powerful tool for creating flexible and reusable code that can work with various data types. However, ensuring type safety is crucial to prevent runtime errors and maintain code reliability. These are the following approaches:Table of Content Using Type const
4 min read
How to Define Static Property in TypeScript Interface?
A static property in a class is a property that belongs to the class itself, rather than to instances of the class. It is shared among all instances of the class and can be accessed without creating an instance of the class. Static properties are defined using the static keyword in front of the prop
3 min read
How do I dynamically assign properties to an object in TypeScript?
In TypeScript, we can not assign the properties dynamically to an object directly by using the dot operator and the square brackets syntax which we generally use to assign dynamic properties in Vanilla JavaScript. JavaScript is a dynamically typed language and the type of a variable is determined at
3 min read
How to Define a Regex-Matched String Type in TypeScript ?
Defining a regex-matched string type in TypeScript means creating a type that ensures a string adheres to a specific regular expression pattern. This enhances type safety by validating strings at compile or runtime, ensuring they match predefined formats. What is a Regex-Matched String?A "regex-matc
4 min read
How to Exclude Property from Type in TypeScript ?
In Typescript, sometimes we need to exclude a property from a type when we want a similar type with some properties excluded or if we want to remove a property from the type. There are several approaches to exclude properties from a type in typescript: Table of Content Using Mapped Types with condit
4 min read
How to Check the Type of an Object in Typescript ?
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below. Table of Content Using
3 min read
How to Deep Clone an Object & Preserve its Type with TypeScript ?
In TypeScript, deep cloning an object by preserving its type consists of retaining the same structure and type information as of original object. Below are the approaches to Deep Clone an Object & Preserve its Type: Table of Content Using JSON.stringify and JSON.parseUsing Object.Assign function
4 min read
How to Declare Specific Type of Keys in an Object in TypeScript ?
In TypeScript, object definitions can include specific key-value types using index signatures. You can declare specific types of keys in an object by using different methods as listed below: Table of Content Using Mapped TypesUsing InterfaceUsing Inline Mapped Types with typeUsing Record Utility Typ
3 min read