Map and Set
Map<K, V> and Set<T> are the standard ES collections, typed with generics. .get returns V | undefined. .has is a boolean and does not narrow the map's value type by itself.
Detailed Explanation
TypeScript does not invent Map and Set. It types the ones in JavaScript. new Map<string, User>() stores User values under string keys. new Set<Role>() stores a unique collection of Role. The generics default to unknown (or are inferred from the constructor argument) so new Map() is Map<any, any> in older lib targets and a more conservative inference in newer ones — pass the type arguments or an initial array of entries.
The important type details:
map.get(key)isV | undefined. The compiler does not track that you just calledhas. Store the result:const user = map.get(id); if (user) ....map.set(key, value)returns the map, so chains type asMap<K, V>.- Iteration is
[K, V]tuples:for (const [id, user] of map). Set<T>.has(x)acceptsTin recent TypeScript (Set<T>.has(value: T)), after years of acceptingany/ a wider type. Passing astringtoSet<number>.hasis now an error, which is what you wanted.- Objects as keys use reference equality.
Map<User, Score>will not find a different object with the sameid. If you meant to key by id, useMap<string, Score>.
ReadonlyMap<K, V> and ReadonlySet<T> are the readonly views: get, has, size, iteration, no set / add / delete. They are types, not runtime classes. A Map is assignable to ReadonlyMap; the reverse is not.
WeakMap and WeakSet are typed too, with the restriction that keys / values must be objects (or symbols, for WeakMap keys in recent ES). See weak collections. They do not iterate, so there is no typed entry tuple.
Do not annotate Map<string, V> and then use an object as a map ({ [id]: user }) at the value level without converting. The types will not line up, and JSON.stringify on a Map is {}. Convert at the boundary: Object.fromEntries(map) is Record<string, V> if you assert or satisfy that type after you know keys are strings.
Inference from new Map([["usd", 1]]) is Map<string, number> (or a string-literal key, depending on as const). Add the generic if the key or value should be wider: new Map<Currency, number>().
Code Examples
1. Map.get is V | undefined.
// 1. Map.get is V | undefined.
type User = { id: string; email: string };
const users = new Map<string, User>();
users.set("u1", { id: "u1", email: "ada@example.com" });
const found = users.get("u1");
if (found !== undefined) {
console.log(found.email);
}2. Set uniqueness, typed membership.
// 2. Set uniqueness, typed membership.
type Role = "admin" | "editor" | "viewer";
const roles = new Set<Role>(["admin", "editor"]);
function canEdit(role: Role): boolean {
return roles.has(role);
}
console.log(canEdit("editor")); // true
// roles.has("owner");
// Error: Argument of type '"owner"' is not assignable to parameter of type 'Role'.3. Readonly views and conversion at a JSON boundary.
// 3. Readonly views and conversion at a JSON boundary.
function snapshot(map: ReadonlyMap<string, number>): Record<string, number> {
return Object.fromEntries(map);
}
const totals = new Map<string, number>([["usd", 1999]]);
const json = snapshot(totals);Common Gotchas
`has` then `get` does not narrow
TypeScript does not keep a per-key store in the type of the map. Assign `get` to a `const` and narrow that.
`JSON.stringify(map)` is `"{}"`
serialize with `Object.fromEntries` or a custom replacer. The type of a `Map` will not remind you.
Object keys are references
two `{ id: "u1" }` literals are two keys. Use the id string if you meant identity by id.
`new Map()` without arguments infers poorly in some lib versions
write `new Map<string, User>()` at public boundaries.