Skip to main content

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

javascript
const map = new Map<string, number>(); map.set("apples", 5); map.set("bananas", 10); console.log(map.get("apples")); // 5 console.log(map.size); // 2

Here string is the key type, number is the value type. map.get("bananas") returns number | undefined, because the element might be missing.


2. Syntax with generic parameters

The type is declared as:

javascript
Map<KeyType, ValueType>

Examples:

javascript
const userRoles: Map<number, string> = new Map(); userRoles.set(1, "admin"); userRoles.set(2, "user");

or

javascript
const dictionary: Map<string, string[]> = new Map(); dictionary.set("frontend", ["React", "TypeScript", "CSS"]);

3. Basic Map methods

MethodWhat it doesExample
.set(key, value)Add or update an elementmap.set("x", 1)
.get(key)Get a valuemap.get("x") -> 1
.has(key)Check if a key existsmap.has("x") -> true
.delete(key)Remove an elementmap.delete("x")
.clear()Clear the Mapmap.clear()
.sizeNumber of elementsmap.size

Usage example

javascript
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); // 1

4. Iterating a Map

A Map can be iterated in several ways:

javascript
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

javascript
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)); // 100

Unlike Record, Map lets you use objects as keys.


6. Creating a Map with initial data

javascript
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:

javascript
const roles = new Map<number, string>([ [1, "admin"], [2, "user"], ]) as const; // roles.set(3, "guest"); Error

or via ReadonlyMap<K, V>:

javascript
const roles: ReadonlyMap<number, string> = new Map([ [1, "admin"], [2, "user"], ]);

8. Differences between Map and Object / Record

PropertyObject / RecordMap
Keysonly string or symbolany type (including objects, numbers, functions)
Order of elementsnot guaranteedpreserves insertion order
Getting the sizeObject.keys(obj).length.size
Iterationmanually via for...inbuilt-in iteration (for...of, .forEach)
Performance with many elementslowerhigher
Typing in TSvia Record<K,V>via Map<K,V>

Comparison example

javascript
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 Map has .has(), .size, and can use an object as a key:

javascript
const 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 Record for dynamic or non-static keys.

Typing:

javascript
const map: Map<string, number> = new Map();

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.