TypeScript Index Signatures
TypeScript Index Signatures: Typing Dynamic Key-Value Dictionaries
When you know the types of keys and values in an object ahead of time—but not the exact property names—TypeScript index signatures ([key: string]: ValueType) let you type dynamic dictionaries safely. Typical examples include translation tables, HTTP header maps, and cached lookup tables.
Any property access on an index signature expects a matching value type, preventing accidental mixing of numbers and functions in a string map.
Writing Index Signatures and Mixing Known Keys
You can combine fixed required properties with an index signature, as long as every fixed property's type is compatible with the index value type.
interface ScoreBoard {
season: string;
[playerName: string]: number | string;
}
const scores: Record<string, number> = {
amina: 95,
leo: 88,
};
scores["maya"] = 92;
const board: ScoreBoard = { season: "2026-Fall", amina: 95 };
console.log(board.season, scores["amina"]);
The undefined Trap on Dynamic Lookups
By default, reading scores["unknownPlayer"] returns number in TypeScript even though its runtime value is undefined. Include | undefined in the signature ([key: string]: number | undefined) or enable "noUncheckedIndexedAccess": true in tsconfig.json.
Common Mistakes to Avoid
- Expecting
[key: string]: numberto work with fixedtitle: stringcleanly: Fixed fields must match the index signature's return type (number | string), or separate metadata from the nesteditems: Record<string, number>map. - Using plain objects for untrusted user keys: Dynamic keys like
"__proto__"or"constructor"collide withObject.prototypemethods; usenew Map<string, number>()for user-supplied keys. - Forgetting
readonlyon read-only dictionaries: Write{ readonly [key: string]: string }to prevent accidental key assignments.
Frequently Asked Questions
What types are valid as index signature keys?
TypeScript supports string, number, symbol, and template literal patterns like `[data-${string}]: string`.
Should I prefer Record<string, T> or { [key: string]: T }?
Both behave the same for string keys, and Record<string, T> is concise. Use an explicit index signature when mixing known fixed properties or custom key parameter names for documentation.
When is Map<string, T> better than an index signature object?
Use Map when keys are added and deleted frequently, when keys aren't strings, or when keys come from untrusted user input.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.