The keyof and typeof operators are fundamental tools for building dynamic, type-safe code in TypeScript.
typeof Operator
keyof Operator
Combining keyof and typeof
Generic Constraints
Indexed Access Types
Mapped Types with keyof
Key Remapping
Template Literal Types with keyof
ReturnType and Parameters
Real-World Patterns
Discriminated Unions with keyof
Best Practices
Summary
typeof:
✓ Extract type from value
✓ Use with 'as const' for literals
✓ Get function types
✓ Derive types from implementation
keyof:
✓ Get union of object keys
✓ Constrain generic parameters
✓ Build mapped types
✓ Type-safe property access
Combinations:
✓ keyof typeof for value keys
✓ Indexed access T[K]
✓ Mapped types with key remapping
✓ Template literal transformations
Conclusion
The keyof and typeof operators are powerful tools for building type-safe abstractions. Use typeof to derive types from runtime values and keyof to work with object keys as types. Combine them with mapped types, template literals, and indexed access to create sophisticated type transformations that catch errors at compile time while keeping your code DRY.