Initialize and Type a Map in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 17, 2022

banner

Photo from Unsplash

Initialize and Type a Map in TypeScript #

Use the Map() constructor to initialize a Map in TypeScript, e.g. const map1: Map<string, string> = new Map([['name', 'Tom']]). The constructor takes an array containing nested arrays of key-value pairs, where the first element is the key and the second - the value.

index.ts
// ✅ Initialize Map from Array // 👇️ const map1: Map<string, string> const map1: Map<string, string> = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(map1); // ✅ Initialize Map from Object const obj = { name: 'Tom', country: 'Chile' }; const map2 = new Map<string, string>(Object.entries(obj)); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(map2);

The Map() constructor takes an array whose elements are key-value pairs.

The first type we passed to the Map generic when initializing the Map is the key, and the second - the value.

We created a Map that has a key and a value of type string in the examples.

The first example shows how to initialize a Map using arrays of key-value pairs and the second example - how to create a Map from an object.

Here is an example where we set the type of the keys in the Map to string, and the type of the values to string[].

index.ts
// 👇️ const map1: Map<string, string[]> const map1: Map<string, string[]> = new Map([ ['colors', ['blue', 'red', 'green']], ['languages', ['english', 'spanish', 'german']], ]); // ✅ Get value from Map // 👇️ ['blue', 'red', 'green'] console.log(map1.get('colors')); // ✅ Iterate over Map map1.forEach((value, key) => { console.log(value, key); }); // ✅ Check if key exists in Map console.log(map1.has('colors')); // 👉️ true // ✅ Set new key in Map map1.set('countries', ['UK', 'Spain', 'Germany']);

The code snippet shows some of the methods the Map object implements.

Now that we've set the type of the values in the Map to string[], we wouldn't be able to set a value of a different type in the Map.

index.ts
// 👇️ const map1: Map<string, string[]> const map1: Map<string, string[]> = new Map([ ['colors', ['blue', 'red', 'green']], ['languages', ['english', 'spanish', 'german']], ]); // ⛔️ Error: Argument of type 'number' is not // assignable to parameter of type 'string[]'. map1.set('age', 30);

We tried to add a new element to the Map with a value of number and TypeScript errored out.

Note that you don't have to add key-value pairs to a Map when creating it.

You can initialize an empty Map, set its type and add key-value pairs later on in your code.

index.ts
// 👇️ const map1: Map<string, string[]> const map1: Map<string, string[]> = new Map([]); map1.set('colors', ['blue', 'red', 'green']); map1.set('languages', ['english', 'spanish', 'german']); // 👇️ {'colors' => ['blue', 'red', 'green'], // 'languages' => ['english', 'spanish', 'german'] // } console.log(map1);

Something you might often have to do is convert an object to a Map. You can use the Object.entries() method to create a Map from an object.

The Object.entries method returns a two dimensional array, where the nested arrays contain 2 elements - the key and the value.

index.ts
const obj = { name: 'Tom', country: 'Chile' }; // 👇️ [['name', 'Tom'], ['country', 'Chile']] console.log(Object.entries(obj)); // 👇️ const map2: Map<string, string> const map2 = new Map<string, string>(Object.entries(obj)); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(map2);

This is a perfect match, as the Map() constructor expects an array containing nested arrays of key-value pairs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.