What is the keyof operator in TypeScript?
Why Interviewers Ask This
This is a classic screening question for TypeScript roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
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.
Common Mistake
Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong TypeScript candidates.
Previous
What are default parameter values in TypeScript?
Next
What is typeof operator in TypeScript?