The const modifier on type parameters infers literal types instead of widening to general types. Here's how to use it.
Basic Concept#
Object Literals#
Route Definitions#
Event Handlers#
Action Creators#
Tuple Inference#
State Machine#
API Endpoints#
Form Fields#
Validation Rules#
Menu Configuration#
vs as const#
Best Practices#
When to Use:
✓ Route/path definitions
✓ Configuration objects
✓ Action types/creators
✓ State machine definitions
✓ API endpoint definitions
Benefits:
✓ Literal types preserved
✓ Better autocomplete
✓ Type-safe key access
✓ Enables type extraction
Patterns:
✓ Combine with as const for arrays
✓ Use for builder patterns
✓ Define schemas with literals
✓ Create type-safe enums
Avoid:
✗ When widening is desired
✗ For user-provided data
✗ When literals aren't useful
✗ Overusing for simple types
Conclusion#
The const modifier on type parameters preserves literal types instead of widening them. Use it for configuration objects, route definitions, action creators, and any scenario where you want the specific literal types rather than general types like string or number. It's particularly powerful when combined with template literal types and conditional types to extract information from the literal values at the type level.