TypeScript Map - Complete Guide with examples

avatar

Borislav Hadzhiev

Wed Mar 09 20223 min read

banner

Photo by Aral Tasher

TypeScript Map - Complete Guide with examples #

To define a Map object in TypeScript, use a generic to set the type of the Map's keys and values. All of the key-value pairs you add to the Map have to conform to the specified type, otherwise the type checker throws an error.

index.ts
// 👇️ Map with string keys and string | number values const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ]); map1.set('country', 'Germany'); const country = map1.get('country'); console.log(country); // 👉️ "Germany" console.log(map1.has('name')); // 👉️ true map1.delete('name'); console.log(map1.has('name')); // 👉️ false console.log(map1.size); // 👉️ 2 (Map has 2 elements)

We used a generic to declare a Map that has string keys and string or number values.

The syntax that is used to type a Map is - new Map<TypeOfKeys, TypeOfValues>(). For example, new Map<number, string> is a Map object with keys of type number and values of type string.

All of the key-value pairs we add to the Map have to conform to the specified types, otherwise an error is thrown.

index.ts
const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ]); // ⛔️ Error: Argument of type 'boolean' is not // assignable to parameter of type 'string | number'.ts(2345) map1.set('country', true);

We used a union type to set the Map's values to be either strings or numbers, but a boolean value is not a member of the union, so we get an error.

Note that you can initialize a Map with values by passing it an array of key-value pairs.

Because we've typed the values of the Map to be strings or numbers, when we use the Map.get method, we will get back a value of type string, number or undefined.

index.ts
const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ['country', 'Germany'], ]); // 👇️ const country: string | number | undefined const country = map1.get('country'); if (typeof country === 'string') { console.log(country.toUpperCase()); }
The country variable is possibly undefined, because TypeScript can't know in advance whether the Map contains a key country.

The if statement serves as a type guard, because it directly checks for the type of the value. The country variable is guaranteed to be a string in the if block.

You can use the Map.set method to add a key-value pair to the Map.

index.ts
const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ]); map1.set('country', 'Germany'); console.log(map1.get('country')); // 👉️ "Germany" console.log(map1.delete('country')); // 👉️ true console.log(map1.has('country')); // 👉️ false

Make sure that the type of the key and type of the value you passed to the Map.set() method conform to the types you specified when defining the Map.

The code snippet above shows how to use the Map.delete() method to remove a key-value pair from the Map.

The Map.delete() method returns true if an element in the Map object existed and has been removed, otherwise false is returned.

The Map.has() method returns true if the specified key exists in the Map.

You can use the Map.forEach method to iterate over a Map in TypeScript.

index.ts
const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ]); map1.forEach((value, key) => { console.log(value, key); // 👉️ James name, 30 age }); for (const [key, value] of map1) { console.log(key, value); // 👉️ name James, age 30 }

The code snippet above shows how to use the Map.forEach() method and a for...of loop to iterate over a Map.

The for...of loop might be your preferred approach if you have to use the break keyword to exit the loop prematurely. Using the break keyword is not supported in the forEach method.

Something you might often need is to convert the Map's keys or values to an array, because arrays have many useful built-in methods.

index.ts
const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ]); const values = Array.from(map1.values()); console.log(values); // 👉️ ['James', 30] const keys = Array.from(map1.keys()); console.log(keys); // 👉️ ['name', 'age']

We used the Map.values method to get an iterator object containing the values of the Map.

We passed the iterator as the only parameter to the Array.from method.

The Array.from method converts the iterable into an array and returns the new array instance.

Another common thing you might need is to check how many elements a Map has. The Map.size method returns the number of elements in the Map.

index.ts
const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ]); console.log(map1.size); // 👉️ 2 map1.set('country', 'Germany'); console.log(map1.size); // 👉️ 3

If you need to remove all key-value pairs from a Map object, use the Map.clear method.

index.ts
const map1 = new Map<string, string | number>([ ['name', 'James'], ['age', 30], ]); map1.clear(); console.log(map1.size); // 👉️ 0
Use the search field on my Home Page to filter through my more than 1,000 articles.