How to use Conditional Types In Typescript
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.
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: "nikunj@example.com"
};
console.log("Name:", person.name);
console.log("Email:", person.email);
Output:
"Name:", "Nikunj"
"Email:", "nikunj@example.com"
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 (`&`)
Contact Us