The keyof type operator is commonly used in TypeScript, especially when working with generic types, utility types, and when you need to perform operations on the keys of an object or type.
The keyof operator is used to get the union type of all keys of an object or type. It allows you to access the keys of an object as a type, which can be useful in various scenarios, such as:
- Generics: It is often used in conjunction with generics to constrain the input to a function or a generic type. For example:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Here, K extends keyof T ensures that key is a valid key of the object T.
- Utility Types: It is commonly used in TypeScript utility types like
Partial,Pick, andRecordto manipulate and transform types based on their keys. - Accessing Properties Dynamically: It allows you to access object properties dynamically based on the key types. For example:
type Person = {
name: string;
age: number;
};
const person: Person = {
name: "John",
age: 30,
};
function getPropertyByKey<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const nameValue = getPropertyByKey(person, "name"); // "John"
const ageValue = getPropertyByKey(person, "age"); // 30
Overall, the keyof type operator is a powerful feature in TypeScript that enables type-safe manipulation and introspection of object keys, and it is commonly used in many TypeScript codebases and libraries.
Leave a Reply