Sub topic 11
When to use Map instead
This chapter assumes you know index signatures, Record<string, T>, and noUncheckedIndexedAccess from the earlier chapters. It also assumes you are comfortable with undefined in union types and with JavaScript's prototype chain at the level of "objects inherit toString". The goal is to decide when a plain object stops being the right dictionary and a Map should replace it.
What a Map changes
A plain object with an index signature is a convenient dictionary, but it is still an object. It carries inherited properties, it only accepts string and symbol keys at runtime, and it has no built-in size. A Map is a separate built-in collection designed only for key-value storage. Its keys live in internal storage, not in the property namespace of an object.
const counts = new Map<string, number>();
for (const word of ["a", "b", "a"]) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts.get("a")); // 2
console.log(counts.get("z")); // undefined
console.log(counts.size); // 2You write both type arguments, Map<K, V>, and the compiler checks every call against them. counts.set(1, 1) is a compile-time error, because the key type is string.
Lookups are always honest about missing keys
With an index signature, obj[key] has type T unless you turn on noUncheckedIndexedAccess. That flag is global, so it affects every array and index access in the project. Map.prototype.get does not depend on any compiler flag. It always returns V | undefined, so the type matches what happens at runtime.
const ages = new Map<string, number>([["ann", 30]]);
const age = ages.get("ann"); // number | undefined
if (age !== undefined) {
console.log(age.toFixed(0));
}Existence checks are also simpler. ages.has("ann") asks only about the map's own entries, so you do not need to choose between in and Object.hasOwn.
Inherited keys cannot leak in
The prototype pitfall from earlier chapters comes from keys that live on Object.prototype. A Record<string, number> claims every string key maps to a number, but some of those keys are really functions.
const obj: Record<string, number> = {};
const fromObject = obj["toString"]; // typed number
console.log(typeof fromObject); // "function"
const map = new Map<string, number>();
console.log(map.get("toString")); // undefined
console.log(map.has("hasOwnProperty")); // false
map.set("toString", 1);
console.log(map.get("toString")); // 1The object version lies to the type checker. The Map version has no such problem. You also avoid special keys such as __proto__. On an ordinary object, assigning obj["__proto__"] = ... changes the prototype instead of creating a key. A Map stores it as an ordinary entry. This matters whenever keys come from user input, such as words in a text, query parameter names, or usernames.
A null-prototype object (Object.create(null)) also removes inherited keys. It still has string-and-symbol keys only, no size, and no iteration helpers. It fixes one problem, while Map fixes all of them.
Keys are not limited to strings
Object keys are always converted to strings (or kept as symbols). A Map keeps the key as it is, and the type parameter can be any type.
const o: Record<string, string> = {};
o[1] = "one";
console.log(Object.keys(o)); // ["1"]
const byId = new Map<number, string>([[1, "one"]]);
console.log(byId.get(1)); // "one"
// byId.get("1"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.In the object, the number 1 and the string "1" are the same key. In the map they are different keys, and the compiler stops you from mixing them up.
Object keys work as well:
interface User {
id: number;
name: string;
}
const alice: User = { id: 1, name: "Alice" };
const sameAlice: User = { id: 1, name: "Alice" };
const visits = new Map<User, number>();
visits.set(alice, 1);
console.log(visits.get(alice)); // 1
console.log(visits.get(sameAlice)); // undefinedMap compares keys by identity for objects, using the SameValueZero algorithm. Two structurally equal objects are different keys. Primitives compare by value, and NaN equals NaN. If you want value-based lookup for objects, derive a string key, such as ` ${user.id} `, and use that as the key.
A Map holds a strong reference to every object used as a key. If you attach data to objects and want it to disappear when the object is garbage collected, WeakMap is the right tool. WeakMap accepts only object keys and cannot be iterated.
Iteration order and size
A Map iterates in insertion order for all keys. An object orders integer-like keys first, in ascending numeric order, and then other string keys in insertion order.
const o: Record<string, string> = { b: "x", 2: "two", a: "y", 1: "one" };
console.log(Object.keys(o)); // ["1", "2", "b", "a"]
const m = new Map<string | number, string>([
["b", "x"],
[2, "two"],
["a", "y"],
[1, "one"],
]);
console.log([...m.keys()]); // ["b", 2, "a", 1]
console.log(m.size); // 4If the order of entries matters, such as in a least-recently-used cache or an ordered log of IDs, Map gives you the order you inserted. m.size is a property. For an object you have to build an array with Object.keys(o).length.
Adding and removing keys
delete obj[key] works, but it is a property deletion on an object, and engines may treat objects that change shape often differently from objects with a fixed set of properties. Map is designed for this workload. It has set, delete, and clear, and the API tells readers the collection is meant to change. For a dictionary that grows and shrinks at runtime, Map is the natural choice. For a small fixed set of keys, either works, and you should not expect to see a measurable difference.
Where Map is worse
Map has real costs, and they decide many cases in practice.
- No JSON support.
JSON.stringify(new Map([["a", 1]]))returns"{}". You must convert explicitly. - No literal syntax. You build maps from arrays of pairs or with repeated
setcalls, and the result is harder to read for configuration data. - One value type.
Map<string, string | number>cannot say thatnameis a string andretriesis a number. Objects with known properties are better typed as interfaces. - No property access. You write
m.get("a"), notm.aorm["a"], and you cannot destructure a map. - Extra runtime weight. Maps need the
Mapbuilt-in, which every current runtime has, but the code is less familiar to some readers.
Converting at the boundary solves the JSON problem:
const settings = new Map<string, number>([["retries", 3]]);
const json = JSON.stringify(Object.fromEntries(settings));
console.log(json); // {"retries":3}
const parsed = JSON.parse(json) as Record<string, number>;
const back = new Map(Object.entries(parsed));
console.log(back.get("retries")); // 3Object.fromEntries needs lib to include ES2019 or later. Object.entries needs ES2017. The cast on JSON.parse is a promise you make to the compiler and nothing checks it, so validate untrusted input before you rely on it.
A helper for default values
A common dictionary pattern is "get the value, or create it first". When the value type itself can include undefined, comparing the result of get to undefined gives the wrong answer. Use has for the existence check.
function getOrCreate<K, V>(map: Map<K, V>, key: K, create: () => V): V {
if (map.has(key)) {
return map.get(key) as V;
}
const value = create();
map.set(key, value);
return value;
}
const groups = new Map<string, string[]>();
getOrCreate(groups, "fruit", () => []).push("apple");
getOrCreate(groups, "fruit", () => []).push("pear");
console.log(groups.get("fruit")); // ["apple", "pear"]The as V cast is safe here, because has returned true and the map therefore holds a V for that key.
Comparing the options
| Need | Index signature or `Record<string, T>` | `Map<K, V>` | Column |
|---|---|---|---|
| Keys come from untrusted input | Risky unless you use `Object.hasOwn` or a null prototype | Safe | |
| Keys are not strings | Not supported at runtime | Any type | |
| Missing-key type | `T` unless `noUncheckedIndexedAccess` is on | Always `V \ | undefined` |
| Size | `Object.keys(o).length` | `m.size` | |
| Entry order | Integer-like keys first | Insertion order | |
| JSON round trip | Built in | Needs conversion | |
| Literal syntax and dot access | Yes | No | |
| Frequent adds and deletes | Works | Designed for it |
Deciding
As a rule of thumb:
- If you know the keys at compile time, use an interface or
Recordwith a union of literal keys. The compiler then checks that every key is present. - If the data crosses a JSON boundary, such as an API response or a config file, type it as an index signature or
Record<string, T>, turn onnoUncheckedIndexedAccess, and useObject.hasOwnfor existence checks. - If the dictionary is built and changed at runtime, or keys come from user input, or keys are not strings, use
Map.
Exercise
A word-frequency counter reads words from user-submitted text and stores counts in const counts: Record<string, number> = {}. Given the input words ["constructor", "constructor"], the code counts[w] = (counts[w] ?? 0) + 1 produces a wrong result. Why, and how would you fix it using a Map?
Show answer
counts["constructor"] is not undefined. It is the inherited Object constructor function, so ?? 0 never applies and the code computes function + 1, which gives a string. The type checker misses this because the index signature promises a number. Use const counts = new Map<string, number>() and counts.set(w, (counts.get(w) ?? 0) + 1). A Map has no inherited keys, so get("constructor") is undefined on the first lookup and the counts come out as 2.
Exercise
You store Map<string, number> settings and need to save them as JSON and load them again. Write the two conversions, and say what JSON.stringify returns if you pass the map directly.
Show answer
Save with JSON.stringify(Object.fromEntries(settings)) and load with new Map(Object.entries(JSON.parse(text) as Record<string, number>)). Passing the map directly returns "{}", because a Map has no enumerable own properties.