KeyOf Operator Flashcards
1
Q
Q: What is the keyof type operator in TypeScript and what does it return?
A
A: The keyof operator takes an object type and produces a union type of its keys (either string or numeric literals). It returns all property names as a union.
type Point = { x: number; y: number }; type PointKeys = keyof Point; // type PointKeys = "x" | "y" // Usage example function getPropertyValue<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
2
Q
Q: What are some practical use cases for the keyof operator?
A
A: The keyof operator is commonly used in generic functions to ensure type safety when accessing object properties and in mapped types.
// Type-safe object property access function pluck<T, K extends keyof T>(obj: T, keys: K[]): T[K][] { return keys.map(key => obj[key]); } interface Person { name: string; age: number; } const person: Person = { name: "John", age: 25 }; const values = pluck(person, ["name"]); // Type safe: ["name"] must be keys of Person