Index signatures
Concept and syntax
An index signature such as { [key: string]: number | undefined } describes the values associated with arbitrary string keys. It does not guarantee every key exists. Include undefined in the value type if lookup may fail, then check before using the result. noUncheckedIndexedAccess can also add undefined to unchecked reads of index signatures. Named properties in the same shape must be compatible with its string index contract.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const stock: { [key: string]: number | undefined } = { tea: 0, coffee: 4 };function read(key: string): number { const n = stock[key]; return n === undefined ? -1 : n;}console.log(read("tea"), read("coffee"), read("milk"));Expected output (one line per log):
0 4 -1Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
const stock: { [key: string]: number | undefined } = { tea: "many" };Expected compiler diagnostic: TS2322. The dictionary value must be numeric or undefined, not arbitrary text.
Practice and recap
Add a stock entry with value zero. Read it and a missing key with the same safe lookup function. Explain the difference.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Index signatures — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Does a string index signature guarantee every key exists at runtime?
Why compare n === undefined instead of if (!n)?
Which value can replace "many" in the dictionary?
const stock: { [key: string]: number | undefined } = { tea: "many" };