Web Analytics

keyof Operator

Advanced~18 min

The keyof operator creates a union type of all property keys in an object type, enabling type-safe property access.

keyof Operator

Output
Click Run to execute your code
keyof Syntax: keyof T creates a union of all keys in type T

Common Use Cases

  • Type-safe property access: Ensure keys exist
  • Generic constraints: Limit to valid keys
  • Mapped types: Transform object types
  • Utility functions: Object manipulation

Common Mistakes

1. Using String Instead of keyof

// โœ— Wrong - allows any string
function get(obj: T, key: string) {
    return obj[key];  // Unsafe!
}

// โœ“ Correct - only valid keys
function get(obj: T, key: K) {
    return obj[key];  // Type-safe!
}
Best Practice: Use keyof with generics for type-safe property access.

Summary

  • keyof T creates union of all keys
  • Perfect for type-safe property access
  • Combine with generics for flexibility
  • Essential for mapped types