Working with Index Signatures


Working with Index Signatures#
In TypeScript, index signatures allow you to define object types with dynamic keys. This is useful when you don’t know all property names in advance or when keys are generated dynamically.
What Are Index Signatures?
An index signature describes the type of keys and the corresponding value types for an object:
interface StringMap {
[key: string]: string;
}
const translations: StringMap = {
hello: "Hola",
goodbye: "Adiós",
};Here, any string key maps to a string value.
String vs Number Index Signatures
You can define index signatures for string or number keys:
interface NumberMap {
[index: number]: string;
}
const names: NumberMap = ["Alice", "Bob", "Charlie"];
console.log(names[1]); // BobNote: Number index signatures also allow string keys because JavaScript coerces number keys to strings.
Using Record Types
TypeScript’s built-in Record utility type is a concise way to define index signatures:
type PhoneBook = Record<string, number>;
const contacts: PhoneBook = {
Alice: 1234567890,
Bob: 9876543210,
};Record<K, T> creates a type with keys of type K and values of type T.
Best Practices
- Prefer
Recordfor simple dynamic key-value types. - Use explicit index signatures when you need more control or additional properties.
- Combine index signatures with known properties carefully.
Tip: Remember that number index signatures imply string index signatures, but not vice versa.
Common Pitfalls
- Overly broad index signatures can reduce type safety.
- Conflicts between index signatures and explicitly declared properties.
- Forgetting that keys are coerced to strings in JavaScript objects.
Next Steps
Next, explore utility types and advanced type manipulation to further enhance your TypeScript skills.
Questions about index signatures or dynamic keys? Share your thoughts or examples in the comments!