JS Built-ins
TypeScriptbeginner

Utility Types β€” keyof Operator

πŸ“– Usage Example
interface User { name: string; age: number }
type UserKey = keyof User   // β†’ 'name' | 'age'
function getField(u: User, k: UserKey) { return u[k] }

keyof produces a union of an object type's property names, enabling type-safe property access.

The keyof Operator

keyof T produces a union of all property names of T.

Challenge: Implement getKeys<T extends object>(obj: T): (keyof T)[] returning all own keys.

getKeys({ a: 1, b: 2, c: 3 })  // β†’ ['a', 'b', 'c']
πŸ’‘ Hints (1)
  • β€’ Object.keys returns string[] β€” cast it to (keyof T)[].