Index Signature
A string index signature `{ [k: string]: V }` types a dictionary of arbitrary string keys. It's backed by a map, so bracket read/write and Object.keys all work — no fixed field set required.
interface Scores {
[player: string]: number;
}
const scores: Scores = { alice: 10, bob: 7 };
scores["carol"] = 12;
console.log(scores["alice"]); // 10
console.log(scores["carol"]); // 12
let total = 0;
for (const name of Object.keys(scores)) {
total += scores[name];
}
console.log(total); // 29
// The inline object-type form works the same way.
type Env = { [key: string]: string };
const env: Env = { HOME: "/root" };
env["SHELL"] = "/bin/sh";
console.log(env["HOME"] + " " + env["SHELL"]); // /root /bin/sh
// Number index signature: keys stringify (JS object keys are strings).
interface Sparse { [i: number]: string; }
const sparse: Sparse = {};
sparse[7] = "seven";
console.log(sparse[7]);
// Logical assignment works against a computed key (ADR-00600): ??= fills a key
// only when it's absent/null, ||= when the current value is falsy.
const cache: { [k: string]: string } = {};
cache["a"] = "hit";
cache["a"] ??= "miss"; // present → stays "hit"
cache["b"] ??= "miss"; // absent → "miss"
console.log(cache["a"], cache["b"]);View source on GitHubexamples/types/index-signature.ts