
Ts Keyof in TypeScript
In TypeScript, keyof is a type operator that is used to obtain the keys of a given type as a union type. It allows you to get a type that represents the set of property names of a given object or interface.
Here’s a basic example:
Example 1: keyof with an interface
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // "name" | "age"
In the above example, PersonKeys is a type that can be either "name" or "age", which are the keys of the Person interface.
Example 2: Using keyof with a function
You can also use keyof to restrict the arguments of a function to only the keys of a certain object.
function getValue<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const person = { name: 'John', age: 30 };
const name = getValue(person, 'name'); // Type: string
const age = getValue(person, 'age'); // Type: number
In this case, K extends keyof T, which means that the key parameter must be one of the keys of the obj.
Example 3: keyof with dynamic types
type User = {
id: number;
username: string;
};
type UserKeys = keyof User; // "id" | "username"
In summary, keyof is a powerful tool for working with the keys of objects, especially when working with types dynamically or enforcing stricter type safety for object properties.