Sub topic 11
When to Use `Map` Instead
Assume you know basic TypeScript types, interfaces, union types, undefined, and JavaScript property access. This chapter compares Map with object dictionaries, such as objects typed with an index signature or Record<string, T>.
A Map<K, V> is a collection that stores values under keys. K is the key type, and V is the value type. Unlike an object dictionary, a Map has methods for inserting, reading, deleting, and checking entries.
The Basic `Map` Model
Create a map by providing its key and value types:
const counts = new Map<string, number>();
for (const word of ["red", "blue", "red"]) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts.get("red")); // 2
console.log(counts.get("green")); // undefined
console.log(counts.size); // 2set adds or replaces an entry. get reads an entry. If the key is absent, get returns undefined. The ?? operator supplies a default when the result is undefined.
Use has when you need to distinguish a missing key from a key whose value is itself undefined:
const settings = new Map<string, string | undefined>();
settings.set("theme", undefined);
console.log(settings.has("theme")); // true
console.log(settings.has("language")); // falseWhy Choose `Map`?
Map is often a better choice when the collection is a dynamic lookup table rather than a data object.
Use it when:
- Keys are added and removed frequently.
- Keys are not limited to strings.
- You need reliable
size, iteration, or deletion operations. - You want to avoid inherited object properties.
- A missing value must be checked explicitly with
has. - Keys can be objects, where object identity matters.
A Map can use numbers, objects, arrays, and other values as keys:
type User = { id: number };
const first: User = { id: 1 };
const second: User = { id: 1 };
const sessions = new Map<User, string>();
sessions.set(first, "active");
console.log(sessions.get(first)); // "active"
console.log(sessions.get(second)); // undefinedfirst and second have the same contents, but they are different object references. Map treats them as different keys.
Object keys behave differently. JavaScript converts most object property keys to strings, so object[1] and object["1"] refer to the same property. A Map<number, V> keeps the number as a number.
Iteration and Cleanup
Map provides direct methods for common collection operations:
const prices = new Map<string, number>([
["book", 12],
["pen", 2],
]);
for (const [name, price] of prices) {
console.log(`${name}: $${price}`);
}
prices.delete("pen");
console.log(prices.size); // 1
prices.clear();
console.log(prices.size); // 0Iteration follows insertion order. This makes the intended operation clear and avoids separately checking own properties before iterating.
`Map` Versus Object Dictionaries
Objects work well for JSON-shaped data and values that will cross an API boundary. They are easy to serialize:
const scores: Record<string, number> = {
alice: 90,
bob: 85,
};
console.log(JSON.stringify(scores));Map does not serialize to useful JSON by default. JSON.stringify(new Map([["alice", 90]])) produces {}. Convert it first if necessary:
const scores = new Map<string, number>([
["alice", 90],
["bob", 85],
]);
const json = JSON.stringify(Object.fromEntries(scores));
console.log(json); // {"alice":90,"bob":85}An object dictionary can also accidentally expose inherited names such as toString. A Map stores only entries that you explicitly add, so has("toString") is false unless you inserted that key.
A Practical Decision
Use an index signature or Record<string, T> for a string-keyed object that represents data and may be serialized. Use Record<Union, T> or a mapped type when the allowed keys are known at compile time. Use Map<K, V> for a mutable runtime collection with arbitrary key types and collection-focused operations.
Exercise
Why does Map<string, number> suit a counter that frequently adds, removes, and checks arbitrary word keys?
Show answer
Map provides set, delete, has, size, and get operations, avoids inherited object keys, and makes a missing lookup explicit through undefined.