The Analogy: The Left-Luggage Office at a Railway Terminus
The left-luggage office runs two systems side by side. The first is the open counter: a traveller hands over a parcel, the clerk writes a stub, tears it in half, and gives one half back. The stub carries a number, and any number the pad prints is valid, so the clerk has no list drawn up in advance of which numbers exist. Whatever ticket you present, the clerk will look on the shelf for a parcel filed under it. The rule of the counter is only this: every stub is a string of digits, and every shelf slot holds a parcel. It says nothing about which particular numbers are in use at any moment.
Along the back wall is the second system, a bank of named lockers for the terminus's season-ticket holders. There is one locker for each name on the roster, the names are known and fixed, and the porter can tell you at a glance whether every holder's locker has been serviced this morning, because there is a finite list to check against. If the company signs a new season-ticket holder, a locker has to be built and labelled before the roster is complete; you cannot have a holder with no locker. The wall is closed where the counter is open: it trades the freedom to take any parcel for the certainty that every name is accounted for.
That is the whole difference. The open counter takes anyone's parcel and files it under any number, but presented with a random stub it cannot promise the shelf slot is occupied, only that if a parcel is there it will be a parcel. The closed wall cannot take a stranger's bag at all, but it can be audited: run down the roster and every name either has its locker in order or does not, with nothing left ambiguous. One buys room at the cost of certainty; the other buys certainty at the cost of room.
The failure mode is the clerk who reads the stub number as proof the parcel is on the shelf. A traveller presents ticket 4051, the clerk sees a well-formed number, turns to the shelf confident a parcel is filed there, and finds the slot empty because that parcel was collected an hour ago. The number existing on the ledger was never the same fact as the parcel existing on the shelf, but the two look identical from behind the counter: a valid-looking stub and a slot that may or may not still hold anything. A clerk who forgets that hands over air, or worse, reaches for the next slot along and hands over somebody else's bag.
Syntax or Core Structure
An index signature declares the shape of keys you cannot enumerate in advance: [ticket: string]: Parcel says every string key maps to a Parcel, without naming a single key. Record<K, V> is the same rule with the key type spelled as a parameter, and when K is a literal union it becomes the closed wall: every named key is required.
// src/luggage.ts
interface Shelf {
[ticket: string]: number; // any stub number -> grams stored
}
type Holder = "cape" | "moor" | "dale";
type Wall = Record<Holder, number>; // exactly these three keys, all required
const shelf: Shelf = { "4051": 2400 };
shelf["4052"] = 1500; // any string key is accepted
const wall: Wall = { cape: 7, moor: 5, dale: 4 };
// const gap: Wall = { cape: 7, moor: 5 }; // refused: 'dale' is missing
console.log(shelf["4051"], shelf["4052"], Object.keys(shelf).length);
console.log(wall.cape + wall.moor + wall.dale);
Output:
2400 1500 2
Output (second line):
16
Output (tsc, for the commented line):
error TS2741: Property 'dale' is missing in type '{ cape: number; moor: number; }' but required in type 'Wall'.
Shelf accepts "4051" and "4052" and any other string with no complaint, which is the open counter. Wall is Record<Holder, number> over a three-name union, so the commented literal is refused for leaving dale out: that is the closed wall being audited at compile time. Record<string, number> would be the exact same rule as the Shelf index signature, spelled as a type alias rather than an interface; the power appears only when the key type is a finite union.
Technical Depth: What the Rule Covers and What It Does Not
The index signature is a promise about the type of every value, and nothing at all about which keys are present. That gap is where the runtime crash lives; and a named property, once you add one, must itself obey the signature.
The signature lies about presence
Ask an index-signature object for a key and TypeScript hands back the value type with a straight face, whether or not the key is there. The stub looks valid, so the type checker assumes the parcel is on the shelf.
// src/lie.ts
const shelf: Record<string, number> = { "4051": 2400 };
const grams = shelf["9999"]; // typed number; actually undefined at runtime
console.log(grams); // prints undefined, not a number
// grams.toFixed(2); // compiles, then throws at runtime
Output:
undefined
The value grams is typed number, so grams.toFixed(2) sails through the compiler and then throws Cannot read properties of undefined when it runs. This is the single commonest runtime crash in a codebase that considers itself fully typed. There are two ways to close it: turn on noUncheckedIndexedAccess, after which every indexed read is number | undefined and the compiler forces a check; or type the value as number | undefined yourself and narrow before use. This project ships with the flag off, so the sample programs below guard their lookups by hand.
A named property must fit the signature
Because the signature is a promise about every key, any property you also name by hand has to be assignable to the value type. A number signature admits a count: number and refuses a desk: string.
// src/mixed.ts
interface Ledger {
[ticket: string]: number; // every value is a number
count: number; // fine: number fits
// desk: string; // refused: 'string' is not assignable to 'number'
}
const led: Ledger = { count: 0, "4051": 2400, "4052": 1500 };
led.count = Object.keys(led).length - 1; // do not count 'count' itself
console.log(led.count, led["4051"]);
Output:
2 2400
The usual escape, when you genuinely need mixed values, is to widen the signature to a union so the named properties fit:
interface Flexible {
[key: string]: number | string; // widened
count: number; // fits the union
label: string; // now allowed
}
The cost is that every indexed read is now number | string, so you narrow before doing arithmetic. Widening the signature buys the extra property back at the price of a looser value type everywhere else.
Keys are strings underneath
A number index signature is a convenience, not a runtime fact: JavaScript object keys are always strings, so a numeric key is coerced to its string form the moment it goes in, and Object.keys hands it back as a string.
// src/numeric.ts
const shelf: Record<number, string> = { 1: "cape", 2: "moor" };
const keys = Object.keys(shelf); // ["1", "2"] at runtime -- strings
console.log(keys.join(","), typeof keys[0]);
console.log(shelf[1], shelf["1"]); // 1 and "1" reach the same slot
Output:
1,2 string
cape cape
Both reads land on the one slot because shelf[1] is evaluated as shelf["1"]. This is why a Map is the honest choice when you truly want numeric or object keys kept as they are: a plain object cannot hold them.
Index signature, Record and Map, side by side
The three tools overlap, and the choice turns on whether the key set is open, closed, or genuinely dynamic.
| Concern | [k: string]: V | Record<K, V> | Map<K, V> |
|---|---|---|---|
| Which keys | any string | exactly K, can be a union | any type, objects included |
| Exhaustiveness check | no | yes, with a literal union | no |
| Insertion order kept | no | no | yes |
| Real size and has() | no | no | yes |
| Survives JSON.stringify | yes | yes | no |
Reach for Record<LiteralUnion, V> when the keys are known, for a string-keyed signature when they are genuinely open, and for a Map when keys are dynamic and you want has, delete and size to mean something.
Real World Example: The Cloakroom Ledger
The cloakroom takes deposits under arbitrary ticket strings, so the shelf is an open index-signature object; the owners are a closed union, so the by-owner tally can be audited. Collecting a bag has to tell three cases apart that all look alike through a raw lookup: a live parcel, a ticket that was collected already, and a ticket that never existed.
// src/cloakroom.ts
type Owner = "cape" | "moor" | "dale" | "vale";
type Deposit = { kind: "deposit"; ticket: string; owner: Owner; grams: number };
type Collect = { kind: "collect"; ticket: string };
type Op = Deposit | Collect;
const OPS: readonly Op[] = [
{ kind: "deposit", ticket: "A1", owner: "cape", grams: 2400 },
{ kind: "deposit", ticket: "A2", owner: "vale", grams: 900 },
{ kind: "deposit", ticket: "A3", owner: "moor", grams: 1500 },
{ kind: "deposit", ticket: "A4", owner: "cape", grams: 700 },
{ kind: "deposit", ticket: "A5", owner: "dale", grams: 1200 },
{ kind: "collect", ticket: "A2" },
{ kind: "collect", ticket: "A9" },
{ kind: "collect", ticket: "A2" }
];
const OWNER_ORDER: readonly Owner[] = ["cape", "moor", "dale", "vale"];
function pad(text: string, width: number): string {
return text.length >= width ? text : text + " ".repeat(width - text.length);
}
function run(ops: readonly Op[]): string {
const shelf: Record<string, number> = {}; // ticket -> grams, held now
const owners: Record<string, Owner> = {}; // ticket -> owner, ever seen
const collected: Record<string, number> = {}; // ticket -> grams, taken away
const order: string[] = []; // deposit order, for the sheet
let deposits = 0;
let taken = 0;
let attempts = 0;
for (const op of ops) {
if (op.kind === "deposit") {
shelf[op.ticket] = op.grams;
owners[op.ticket] = op.owner;
order.push(op.ticket);
deposits += 1;
continue;
}
attempts += 1;
const held = shelf[op.ticket]; // typed number, but really may be undefined
if (held === undefined) { continue; } // unknown ticket, or already gone
collected[op.ticket] = held;
delete shelf[op.ticket];
taken += 1;
}
const out: string[] = [];
out.push(pad("TICKET", 8) + pad("OWNER", 7) + pad("GRAMS", 7) + "STATUS");
let heldGrams = 0;
let collectedGrams = 0;
for (const ticket of order) {
const owner = owners[ticket];
const onShelf = shelf[ticket];
if (onShelf === undefined) {
const g = collected[ticket];
collectedGrams += g;
out.push(pad(ticket, 8) + pad(owner, 7) + pad(String(g), 7) + "collected");
} else {
heldGrams += onShelf;
out.push(pad(ticket, 8) + pad(owner, 7) + pad(String(onShelf), 7) + "held");
}
}
const byOwner = OWNER_ORDER
.map((o) => [o, order.filter((t) => owners[t] === o && shelf[t] !== undefined).length] as const)
.filter(([, n]) => n > 0)
.map(([o, n]) => o + " x" + String(n));
out.push("deposits: " + String(deposits) + ", collections: "
+ String(taken) + " of " + String(attempts));
out.push("grams held: " + String(heldGrams) + ", collected: "
+ String(collectedGrams) + ", total: " + String(heldGrams + collectedGrams));
out.push("held by owner: " + byOwner.join(", "));
return out.join("\n");
}
console.log(run(OPS));
Output:
TICKET OWNER GRAMS STATUS
A1 cape 2400 held
A2 vale 900 collected
A3 moor 1500 held
A4 cape 700 held
A5 dale 1200 held
deposits: 5, collections: 1 of 3
grams held: 5800, collected: 900, total: 6700
held by owner: cape x2, moor x1, dale x1
Read the sheet against the two systems. The shelf is a plain index-signature object: tickets A1 through A5 were filed under whatever strings the deposits carried, with no roster drawn up first, which is exactly the open counter. The held === undefined guard is the clerk actually looking on the shelf rather than trusting the stub: it is what lets the collect of A2 succeed once, the second collect of A2 fail because the slot was deleted, and the collect of A9 fail because it was never filed. All three would look like a valid number through a raw lookup; only the runtime check tells them apart.
The closed union earns its keep in the last line. held by owner walks OWNER_ORDER, a finite list of four names, and reports every owner that still holds a bag: cape twice, moor and dale once each, with vale dropping out because its only parcel was collected. That tally can be trusted to be complete precisely because Owner is a union and not an open string: there is a fixed set to iterate. The shelf could never be audited that way, because there is no list of which ticket strings might exist.
The totals split held from collected on purpose. grams held counts only what is still on the shelf, collected counts what has left, and total is the sum, so the report never pretends a collected bag is still present. That is the absent-versus-recorded distinction from the optional-property lesson, made concrete: an empty shelf slot and a collected ticket are different facts, and the ledger keeps a separate record of each rather than reading one blank two ways.
The program has real defects, and they cluster where the open counter meets the runtime. It leans on noUncheckedIndexedAccess being off: the held lookup is typed number yet genuinely returns undefined, and only the hand-written guard saves it, so turning the flag on is the safer posture the code quietly declines. The owners record grows without bound, because a collected ticket is deleted from shelf but never from owners, so a cloakroom that runs all day accumulates a dead entry for every bag ever taken. A second deposit under a ticket string already in use would silently overwrite the first parcel's grams, since nothing checks the slot before writing, and the earlier bag's weight would simply vanish from the totals. And total reads naturally as "grams on the shelf" when it actually means "grams ever deposited", the same figure-that-looks-like-a-balance trap as before, mitigated only by the held and collected fields printed beside it.
Common Mistakes
- Trusting an indexed read to be present: with
noUncheckedIndexedAccessoff,obj[key]is typed as the value type even when the key is absent, so the value isundefinedat runtime and the next method call throws. This is the commonest crash in "fully typed" code. - Reaching for
Record<string, any>as a shrug: it re-creates a plain untyped object with extra ceremony; preferRecord<string, unknown>and narrow, or a literal-union key when you actually know the keys. - Using a string index signature when the key set is closed: if the keys are a known handful,
Record<Union, V>gives you autocomplete and exhaustiveness that an open signature throws away for nothing. - Adding a named property that clashes with the signature: under
[k: string]: numberalabel: stringis refused, because the signature promises every value is a number; widen the value type or drop the extra property. - Using
into test a key and catching inherited members:"toString" in objistruefor every object; useObject.hasOwn(obj, key)to ask only about own keys. - Assuming numeric keys stay numeric:
{ 1: "a" }stores the key as"1",Object.keysreturns["1"], andobj[1]andobj["1"]hit the same slot; use aMapif you need real numeric or object keys. - Confusing an absent key with a removed one: a raw lookup returns the same
undefinedfor "never set" and "deleted", so if the difference matters you must track it separately, as the cloakroom trackscollected. - Iterating a
Recordand expecting a typed key:Object.keyswidens back tostring[], so the loop variable isstring, not your literal union; use a typed helper or a cast you have justified. - Leaving an index-signature object mutable when it should not be: a plain signature allows write and
deletefrom anywhere; mark itReadonly<Record<K, V>>when callers should only read.
Best Practices
- Default to
Record<LiteralUnion, V>and fall back toRecord<string, V>only for genuinely open key sets: the literal union is the closed wall that can be audited. - Turn on
noUncheckedIndexedAccesson new projects: it makes every indexed readV | undefined, which is the truth, and costs only a few??operators to satisfy. - Wrap open-ended lookups in one small accessor: a
getGrams(ticket): number | undefinedkeeps theundefinedhandling in a single place instead of at every call site. - Reach for a
Mapwhen keys are dynamic and you needhas,deleteorsize: a plain object fakes all three and lies about the first. - Use
Object.hasOwnrather thaninfor presence tests: it asks about own properties only and skips the inherited prototype members. - Widen the value type deliberately, not with
any: anumber | stringsignature or aRecord<string, unknown>keeps the door narrow;anyremoves the door. - Keep a separate record when absent and removed must be told apart: one open object cannot express both, so track the second fact explicitly.
- Hand out
Readonly<Record<K, V>>for lookup tables callers should not edit: it blocks write anddeleteat the type level, so a configuration map cannot be mutated by accident.
Practice Exercises
- The Score Board: Build a
Record<string, number>of player scores and atopScorer(): stringthat returns the highest. EnablenoUncheckedIndexedAccess, fix every error it surfaces, and explain in one line why each read was unsafe. - The Exhaustive Wall: Define
type Locale = "en" | "fr" | "de"andconst greetings: Record<Locale, string>, then add"es"to the union and read the error before filling it in; explain what a plainRecord<string, string>would have let slip. - The Mixed Cabinet: Write an interface with a
[k: string]: numbersignature, try to addname: string, read the error, then fix it two ways: widen the value type, and movenameto a separate required property outside the signature. - The Audited Cloakroom: Take
cloakroom.ts, changeshelftoReadonly<Record<string, number>>and rebuild each state with a spread instead ofdelete, then add pruning soownersdrops a ticket when its parcel is collected, and hand-trace the new "held by owner" line.