keyof Operator
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 TCommon 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 Tcreates union of all keys- Perfect for type-safe property access
- Combine with generics for flexibility
- Essential for mapped types
Enjoying these tutorials?