What is the keyof operator in TypeScript?
Answer
The keyof operator creates a union type of all the keys (property names) of a given type. For interface User { name: string; age: number; email: string; }, keyof User produces "name" | "age" | "email". This is useful for creating type-safe functions that access object properties by key: function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }. This ensures that only valid keys of the object can be passed, and the return type is correctly inferred as the type of that property. Without keyof, you would need to use string for the key and any for the return — losing all type safety. keyof works with index signatures: keyof { [key: string]: number } is string | number (because numeric indices are valid in JavaScript). keyof any is string | number | symbol.
Previous
What are default parameter values in TypeScript?
Next
What is typeof operator in TypeScript?