Sub topic 12
Choosing the Right Dictionary Type
The earlier chapters introduced four ways to type an object whose keys are not fixed by hand: index signatures, Record, mapped types, and Map. This chapter gives you a way to pick between them.
It assumes you know the following:
- Index signature syntax, including that known properties must fit the signature's value type.
- The
noUncheckedIndexedAccesscompiler option. Object.hasOwnversus theinoperator.- The prototype pitfalls of plain objects.
The candidates side by side
| Option | Keys | Missing key | Inherited keys | JSON-friendly | Best for | Column |
|---|---|---|---|---|---|---|
| `{ [k: string]: T }` or `Record<string, T>` | string, number, symbol | `T` (or `T \ | undefined` with the flag) | Yes, unless null-prototype | Yes | Data parsed from JSON, open-ended string maps |
| `` { [k: `data-${string}`]: T } `` | Strings matching a pattern | Same as above | Yes | Yes | Prefixed or structured key families | |
| `Record<Union, T>` or a mapped type | A closed set of literals | Compile error if a required key is absent | Not an issue for literal access | Yes | Fixed, known keys | |
| `Map<K, V>` | Any value | `get` returns `V \ | undefined` | No | No, serialize it yourself | Dynamic keys, non-string keys, frequent writes |
Ask four questions
Work through these in order. The first "yes" usually settles the choice.
Question 1: Do you actually know the keys?
If the keys are a closed set, you do not have a dictionary problem. An index signature here throws away information. It accepts typos and never reports a missing key.
type Level = "low" | "high";
const budget: Record<Level, number> = { low: 1, high: 10 };
// Error: Property 'high' is missing in type '{ low: number; }'
// const incomplete: Record<Level, number> = { low: 1 };
console.log(budget.high.toFixed(1)); // 10.0, no undefined check neededWith the literal union, the compiler checks that every key is present. It also rejects budget.medium. Use Partial<Record<Level, number>> when some keys may be absent. A mapped type does the same job when you want to derive the value type from the key:
type Flags = "darkMode" | "beta" | "telemetry";
type FlagState = { [F in Flags]: boolean };
const defaults: FlagState = { darkMode: false, beta: false, telemetry: true };If you add a member to Flags, every object typed as FlagState fails to compile until it is updated. An index signature never gives you that.
Question 2: Are the keys not strings, or do they change constantly?
An object's keys are always strings or symbols. A number key such as 1 is converted to the string "1". A Map keeps the key exactly as you gave it.
const byId: Record<number, string> = {};
byId[1] = "first";
console.log(Object.keys(byId)); // [ '1' ]
const mapById = new Map<number, string>();
mapById.set(1, "first");
console.log([...mapById.keys()]); // [ 1 ]
const owner = { name: "build-42" };
const metadata = new Map<object, string>();
metadata.set(owner, "queued");
console.log(metadata.get(owner)); // queuedAn object cannot use another object as a key. It would be converted to "[object Object]", and every object would collide on that one key.
Choose Map when any of these apply:
- The keys are objects, or you need to tell
1and"1"apart. - Keys come from untrusted input, such as words in user text or request headers.
Maphas no inherited-key problem. - You add and delete entries often. Engines optimize
Mapfor this, while deleting from objects can slow them down. - You need the entry count (
map.size) or guaranteed insertion-order iteration without special rules. Objects order integer-like keys numerically before other keys.
Question 3: Do the keys follow a pattern?
If every key starts with a known prefix, say so in the type. Keys that don't match are then rejected at compile time.
type CssVariables = Record<`--${string}`, string>;
const theme: CssVariables = {
"--bg": "#fff",
"--accent": "#06c",
};
// const bad: CssVariables = { color: "red" }; // Error: not assignableRecord with a template literal key produces the same pattern index signature as writing it out. Pattern signatures also let you combine families of keys in one object through an intersection, such as Record<--${string}, string> & { name: string }.
Question 4: Otherwise, use a string index signature, and harden it
Use a string index signature for data of unknown shape, such as parsed JSON, environment variables, or query strings. Two habits make it safe.
- Turn on
noUncheckedIndexedAccessso reads are typedT | undefined. - Test for presence with
Object.hasOwn, notin.
function readPort(env: Record<string, string>): number {
const raw = env["PORT"]; // string | undefined with the flag enabled
if (raw === undefined) {
return 3000;
}
return Number(raw);
}
function hasSetting(env: Record<string, string>, key: string): boolean {
return Object.hasOwn(env, key);
}Use === undefined when you only want a value. Use Object.hasOwn when the key's presence matters and the stored value could itself be undefined.
A failure that the type system cannot see
Index signatures declare that every string key maps to T. They do not remove the inherited keys that Object.prototype adds. Here is a word counter written the obvious way:
function countWords(words: string[]): Record<string, number> {
const counts: Record<string, number> = {};
for (const word of words) {
counts[word] = (counts[word] ?? 0) + 1;
}
return counts;
}
const result = countWords(["constructor", "a"]);
console.log(typeof result["constructor"]); // stringFor the word "constructor", counts[word] reads the inherited Object function. It is not undefined, so ?? keeps it. Adding 1 turns it into a string such as "function Object() { [native code] }1". The declared type says number, and the compiler reports nothing.
There are three fixes. Which one you pick depends on how much of the code you control.
// Fix 1: a Map, which has no inherited keys
function countWordsMap(words: string[]): Map<string, number> {
const counts = new Map<string, number>();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
// Fix 2: a null-prototype object
function countWordsBare(words: string[]): Record<string, number> {
const counts: Record<string, number> = Object.create(null);
for (const word of words) {
counts[word] = (counts[word] ?? 0) + 1;
}
return counts;
}
// Fix 3: check own keys before reading
function countWordsGuarded(words: string[]): Record<string, number> {
const counts: Record<string, number> = {};
for (const word of words) {
const current = Object.hasOwn(counts, word) ? counts[word] : 0;
counts[word] = (current ?? 0) + 1;
}
return counts;
}Map is the cleanest. The null-prototype object keeps the plain-object shape, but it has no toString or hasOwnProperty methods. Calling String(counts) on it throws. The guard works, but every access site must remember it.
The pitfall only matters when keys come from outside your code. A dictionary keyed by literal names you wrote yourself never sees "constructor".
Trade-offs that decide close cases
Serialization
JSON.stringify turns a Map into {}, because a map's entries are not enumerable properties. If the data crosses a network boundary or lands in storage, convert at the edge:
const settings = new Map<string, number>([["retries", 3]]);
console.log(JSON.stringify(settings)); // {}
console.log(JSON.stringify(Object.fromEntries(settings))); // {"retries":3}
const restored = new Map(Object.entries({ retries: 3 }));
console.log(restored.get("retries")); // 3Object.fromEntries needs lib es2019 or later. A common pattern is plain objects at the boundary and Map inside hot code.
Type narrowing and ergonomics
Property access with dots (config.name) works on objects and reads naturally. Map always needs get and set. Objects can also be spread, destructured, and checked with satisfies, none of which Map supports.
Mixed shapes
When an object has a few known fields plus open-ended extras, an index signature forces every known field to fit the extras' value type. That often widens the value type to string | number, and then reading any field gives you the union. A separate property for the extras often reads better:
interface Widget {
id: number;
label: string;
attributes: Record<string, string>;
}
const widget: Widget = {
id: 7,
label: "Save",
attributes: { "aria-label": "Save file" },
};
console.log(widget.id.toFixed(0)); // known field keeps its exact typeHere widget.id is a plain number, and attributes is free to hold anything of the right type. Use the single-object form only when the data is already shaped that way, such as a JSON payload you cannot change.
Read-only data
If callers should not modify the dictionary, mark it. Use Readonly<Record<string, number>>, or an interface with readonly [key: string]: number. Use ReadonlyMap<K, V> for a map. This is a compile-time guarantee only. It does not freeze the object at runtime.
Common mistakes
- Using
Record<string, T>for a closed set of keys. The compiler stops checking for typos. Use a literal union. - Trusting
Tfor lookups without the flag. WithoutnoUncheckedIndexedAccess,dict["missing"]is typedTbut isundefinedat runtime. - Using
infor own-key checks."toString" in {}istrue. UseObject.hasOwn. - Using a
Mapfor data you need to serialize. Convert at the boundary or use an object. - Expecting
Record<number, T>to keep numbers. The keys still become strings at runtime.
Exercises
Exercise
A function receives HTTP headers as Record<string, string> and must tell whether a header named "constructor" was actually sent. Which check is correct, and why does headers["constructor"] !== undefined give the wrong answer?
Show answer
Use Object.hasOwn(headers, "constructor"). A plain object inherits constructor from Object.prototype, so reading headers["constructor"] returns the Object function even when no such header was sent. The !== undefined test is then true. Object.hasOwn checks only the object's own keys.
Exercise
You are modelling type Role = "admin" | "editor" | "viewer" and need the number of seats allowed for each role. Which type do you declare, and what happens if someone adds "guest" to Role later?
Show answer
Declare Record<Role, number> (or { [R in Role]: number }). When "guest" is added to the union, every object of that type that lacks a guest key fails to compile, so the omission is caught. A Record<string, number> would not report it.
Exercise
A cache is keyed by DOM-like node objects, with entries added and removed constantly. Why can a plain object not be used, and what should you use?
Show answer
An object converts its keys to strings, so every node object becomes "[object Object]" and all entries collide. Use Map<Node, Value>, which keeps object identity as the key and handles frequent adds and deletes.