TypeScript
/Advanced
keyof Operator
Definition
The `keyof` operator takes an object type and produces a string or numeric literal union of its keys.
Explain Like I'm New
Imagine having a massive object with 50 properties. If you want a type that represents 'Any of the keys inside this object', you don't want to type out `'name' | 'age' | 'email' | ...` manually. The `keyof` operator reaches into the object and auto-generates that union for you.
Real World Example
Writing a generic `getProperty(obj, key)` function. You use `keyof` to ensure the developer can only pass a string that ACTUALLY exists as a key on that specific object.
Common Use Cases
- •Dynamic property access
- •Creating highly strict utility functions
Interactive Example
interface User { id: number; name: string; email: string; } // This is identical to: type UserKeys = "id" | "name" | "email" type UserKeys = keyof User; // Powerful Generic use case: T is the object, K is constrained to be a valid key of T function getProperty<T, K extends keyof T>(obj: T, key: K) { return obj[key]; } const person: User = { id: 1, name: "Alice", email: "a@a.com" }; // Valid! Returns a string. const val = getProperty(person, "name"); // ERROR: Argument of type '"age"' is not assignable to parameter of type 'keyof User'. // getProperty(person, "age");
Interview Questions
basic
- What does `keyof User` return if User has `{ id: 1, name: 'A' }`?
intermediate
- How do you use `keyof` in combination with Generics?
advanced
- What does `keyof` return for an Array type?