Q21: What is the `keyof` operator and how is it used?

Difficulty:MediumTopic:Type Operators

The keyof operator produces a union of string or numeric literal types representing the key names of an object type.

keyof Operator Usage
interface User {
  id: number;
  name: string;
  email: string;
}

type UserKeys = keyof User; // Type: 'id' | 'name' | 'email'

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
💡 K extends keyof T guarantees that the provided key argument exists on the target object type T.
Key Takeaways
  • keyof T returns a union of all property name keys belonging to type T.