What is Map in TypeScript?
1. What Map is
Map<K, V>is a data structure that stores key-value pairs and remembers the order in which elements were added.
Unlike a regular {} object, keys in a Map can be of any type, not only strings.
Example
const map = new Map<string, number>();
map.set("apples", 5);
map.set("bananas", 10);
console.log(map.get("apples")); // 5
console.log(map.size); // 2Here
stringis the key type,numberis the value type.map.get("bananas")returnsnumber | undefined, because the element might be missing.
2. Syntax with generic parameters
The type is declared as:
Map<KeyType, ValueType>Examples:
const userRoles: Map<number, string> = new Map();
userRoles.set(1, "admin");
userRoles.set(2, "user");or
const dictionary: Map<string, string[]> = new Map();
dictionary.set("frontend", ["React", "TypeScript", "CSS"]);3. Basic Map methods
| Method | What it does | Example |
|---|---|---|
.set(key, value) | Add or update an element | map.set("x", 1) |
.get(key) | Get a value | map.get("x") -> 1 |
.has(key) | Check if a key exists | map.has("x") -> true |
.delete(key) | Remove an element | map.delete("x") |
.clear() | Clear the Map | map.clear() |
.size | Number of elements | map.size |
Usage example
const points = new Map<string, number>();
points.set("Alice", 10);
points.set("Bob", 20);
console.log(points.has("Bob")); // true
console.log(points.get("Bob")); // 20
points.delete("Alice");
console.log(points.size); // 14. Iterating a Map
A Map can be iterated in several ways:
const users = new Map<number, string>([
[1, "Tim"],
[2, "Max"],
[3, "Bob"],
]);
// for...of
for (const [id, name] of users) {
console.log(id, name);
}
// forEach
users.forEach((name, id) => {
console.log(`${id}: ${name}`);
});
// keys only
for (const key of users.keys()) console.log(key);
// values only
for (const value of users.values()) console.log(value);5. Typing with objects and custom types
interface User {
id: number;
name: string;
}
const userScores = new Map<User, number>();
const tim: User = { id: 1, name: "Tim" };
const max: User = { id: 2, name: "Max" };
userScores.set(tim, 100);
userScores.set(max, 80);
console.log(userScores.get(tim)); // 100Unlike
Record,Maplets you use objects as keys.
6. Creating a Map with initial data
const cities = new Map<string, number>([
["Berlin", 3645000],
["Paris", 2140000],
["Tokyo", 13900000],
]);We pass an array of
[key, value]pairs. TypeScript infers the types automatically.
7. An immutable (readonly) map
If you need to forbid changes:
const roles = new Map<number, string>([
[1, "admin"],
[2, "user"],
]) as const;
// roles.set(3, "guest"); Erroror via ReadonlyMap<K, V>:
const roles: ReadonlyMap<number, string> = new Map([
[1, "admin"],
[2, "user"],
]);8. Differences between Map and Object / Record
| Property | Object / Record | Map |
|---|---|---|
| Keys | only string or symbol | any type (including objects, numbers, functions) |
| Order of elements | not guaranteed | preserves insertion order |
| Getting the size | Object.keys(obj).length | .size |
| Iteration | manually via for...in | built-in iteration (for...of, .forEach) |
| Performance with many elements | lower | higher |
| Typing in TS | via Record<K,V> | via Map<K,V> |
Comparison example
const obj: Record<string, number> = { apples: 10, bananas: 5 };
const map: Map<string, number> = new Map([
["apples", 10],
["bananas", 5],
]);
obj["oranges"] = 7;
map.set("oranges", 7);But
Maphas.has(),.size, and can use an object as a key:javascriptconst key = { id: 1 }; map.set(key, 123); // fine
Summary
Map<K, V>is a collection of key-value pairs with any key type and a guaranteed order.The basics:
- Keys can be of any type (unlike objects).
- Uses the generic syntax
Map<KeyType, ValueType>.- Fast lookup and iteration.
- Often used instead of
Recordfor dynamic or non-static keys.Typing:
javascriptconst map: Map<string, number> = new Map();
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.