Index signatures allow typing objects with dynamic keys. Here's how to use them effectively.
Basic Syntax#
With Known Properties#
Record Type#
Mapped Types vs Index Signatures#
Generic Dictionaries#
Safe Index Access#
Template Literal Keys#
Readonly Index Signatures#
Discriminated Index Types#
Object.keys and Index Signatures#
Symbol Index Signatures#
Class with Index Signature#
Validation with Index Signatures#
Best Practices#
When to Use:
✓ Dynamic object keys
✓ Dictionary/map patterns
✓ Configuration objects
✓ Cache implementations
Safety:
✓ Enable noUncheckedIndexedAccess
✓ Check for undefined
✓ Use Map for runtime safety
✓ Prefer Record<K, V> syntax
Patterns:
✓ Combine with known properties
✓ Use template literal keys
✓ Consider readonly
✓ Use generics for flexibility
Avoid:
✗ Overly permissive signatures
✗ Ignoring undefined returns
✗ Complex nested signatures
✗ When specific keys are known
Conclusion#
Index signatures type objects with dynamic keys, enabling dictionary patterns and flexible configurations. Use [key: string]: Type for string keys, combine with known properties when needed, and prefer Record<K, V> for cleaner syntax. Enable noUncheckedIndexedAccess for safety, as index access can return undefined. For runtime type safety with dynamic keys, consider using Map instead of plain objects.