The keyof and typeof operators enable powerful type manipulation by extracting types from values and keys. Here's how to use them.
Basic keyof#
Basic typeof#
Combining keyof and typeof#
Object Property Access Types#
Enum-like Objects#
Generic Constraints#
Mapped Types with keyof#
Type Guards with keyof#
Function Parameter Types#
Conditional Types with keyof#
Index Signatures#
Class Types#
Template Literal Types#
Real-World Examples#
Best Practices#
keyof Usage:
✓ Type-safe property access
✓ Generic constraints
✓ Mapped types
✓ Dynamic key validation
typeof Usage:
✓ Extract types from values
✓ Configuration objects
✓ Function return types
✓ Const assertions
Combinations:
✓ keyof typeof for objects
✓ ReturnType<typeof fn>
✓ Parameters<typeof fn>
✓ InstanceType<typeof Class>
Avoid:
✗ Overcomplicating simple types
✗ Ignoring index signatures
✗ Missing const assertions
✗ Excessive type inference
Conclusion#
The keyof and typeof operators are fundamental for TypeScript type manipulation. Use keyof to extract union types of object keys, typeof to derive types from values, and combine them for powerful patterns like enum-like objects and type-safe property access. These operators enable writing generic, reusable code while maintaining full type safety.