Skip to content

TypeScript Map Object

Map is a new data structure introduced in ES6 that is similar to objects, also being a collection of key-value pairs. However, compared to regular objects, Map provides more powerful and flexible functionality, especially regarding key types.

Using Map in TypeScript, you can combine it with generics to specify the types of keys and values, gaining complete type safety support.

Creating a Map

You can use the new Map() constructor to create a new Map. You can specify the types of keys and values.

typescript
// Create a Map with string keys and number values
let studentScores = new Map<string, number>();

You can also initialize data directly when creating, through an array containing key-value pairs (like an array of tuples).

typescript
let initialScores: [string, number][] = [["Alice", 95], ["Bob", 88], ["Charlie", 100]];
let studentScores = new Map<string, number>(initialScores);

Main Features of Map

  1. Keys of any type: Regular object keys can only be strings or Symbols. But Map keys can be values of any type, including functions, objects, or any primitive type.
  2. Ordered: Elements in a Map are arranged in insertion order. When you iterate over a Map, it will be in the order elements were added.
  3. size property: Map directly provides a size property to get the number of key-value pairs, which is more efficient than counting object properties.
  4. Easy to iterate: Map natively supports iteration and can be used directly with for...of loops.

Common Methods and Properties of Map

set(key, value)

Adds or updates a key-value pair in the Map. Returns the Map object itself, so it can be chained.

typescript
studentScores.set("David", 92);
studentScores.set("Alice", 98); // Update Alice's score

console.log(studentScores);
// Map(4) { 'Alice' => 98, 'Bob' => 88, 'Charlie' => 100, 'David' => 92 }

get(key)

Gets the value corresponding to the specified key. Returns undefined if the key doesn't exist.

typescript
let bobScore = studentScores.get("Bob");
console.log(bobScore); // 88

let eveScore = studentScores.get("Eve");
console.log(eveScore); // undefined

has(key)

Checks if the specified key exists in the Map, returns a boolean value.

typescript
console.log(studentScores.has("Charlie")); // true
console.log(studentScores.has("Frank")); // false

delete(key)

Deletes the specified key-value pair. Returns true if successfully deleted; otherwise returns false.

typescript
let didDelete = studentScores.delete("Bob");
console.log(didDelete); // true
console.log(studentScores.has("Bob")); // false

clear()

Clears the Map, removing all key-value pairs.

typescript
studentScores.clear();
console.log(studentScores.size); // 0

size Property

Returns the number of key-value pairs in the Map.

typescript
// Re-add data
studentScores.set("Anna", 99);
studentScores.set("Ben", 91);
console.log(studentScores.size); // 2

Iterating Over a Map

Map provides multiple ways to iterate.

Using for...of Loop

This is the most commonly used iteration method.

typescript
for (let [key, value] of studentScores) {
    console.log(`${key}'s score is ${value}`);
}
// Anna's score is 99
// Ben's score is 91

Using forEach() Method

typescript
studentScores.forEach((value, key) => {
    console.log(`${key}: ${value}`);
});

Iterating Over Keys or Values

  • keys(): Returns an iterator containing all keys.
  • values(): Returns an iterator containing all values.
  • entries(): Returns an iterator containing all [key, value] pairs (for...of internally uses this).
typescript
// Iterate over keys
for (let key of studentScores.keys()) {
    console.log(key);
} // Anna, Ben

// Iterate over values
for (let value of studentScores.values()) {
    console.log(value);
} // 99, 91

Content is for learning and research only.