Dynamic Keys
What
Index signatures allow you to define types for objects where you don’t know the exact property names in advance, but you do know the types of the keys and values.
How
You define an index signature using square brackets within the object type:
type UserMetrics = {
[key: string]: number; // Any string key will map to a number value
};
const metrics: UserMetrics = {
wordsPerMinute: 50,
errors: 2,
};
metrics["timeOnPage"] = 120; // OK
Why
Index signatures are essential for modeling dictionaries, caches, or user-defined configurations where keys are dynamic. They allow you to maintain type safety for the values even when the keys themselves are unpredictable.
Summary
Use index signatures when your object acts as a generic container for a set of values mapped to dynamic keys.