Initialize and Type a Map in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 27, 2024
3 min

banner

# Table of Contents

  1. Initialize and Type a Map using an Array
  2. Initialize and Type a Map using an Object
  3. Typing a Map with values of type array
  4. Declaring an empty typed Map in TypeScript

# Initialize and Type a Map using an Array

Use the Map() constructor to initialize a Map in TypeScript.

The constructor takes an array containing key-value pair arrays, where the first element is the key and the second is the value.

index.ts
// โœ… Initialize Map from Array // ๐Ÿ‘‡๏ธ const map1: Map<string, string> const map1: Map<string, string> = new Map([ ['name', 'Bobby Hadz'], ['country', 'Chile'], ]); // ๐Ÿ‘‡๏ธ Map(2) { 'name' => 'Bobby Hadz', 'country' => 'Chile' } console.log(map1);

initialize and type map using array

The code for this article is available on GitHub

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 is the value.

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

# Initialize and Type a Map using an Object

You can use the Object.entries() method if you need to initialize a type a Map using an object.

index.ts
const obj = { name: 'Bobby Hadz', country: 'Chile' }; const map1 = new Map<string, string>(Object.entries(obj)); // ๐Ÿ‘‡๏ธ Map(2) { 'name' => 'Bobby Hadz', 'country' => 'Chile' } console.log(map1);

initialize and type map using an object

The code for this article is available on GitHub

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: 'Bobby Hadz', country: 'Chile' }; // ๐Ÿ‘‡๏ธ [ [ 'name', 'Bobby Hadz' ], [ 'country', 'Chile' ] ] console.log(Object.entries(obj)); // ๐Ÿ‘‡๏ธ const map1: Map<string, string> const map1 = new Map<string, string>(Object.entries(obj)); // ๐Ÿ‘‡๏ธ Map(2) { 'name' => 'Bobby Hadz', 'country' => 'Chile' } console.log(map1);

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

# Typing a Map with values of type array

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 a key exists in Map console.log(map1.has('colors')); // ๐Ÿ‘‰๏ธ true // โœ… Set a new key in Map map1.set('countries', ['UK', 'Spain', 'Germany']);

typing map with values of type array

The code for this article is available on GitHub

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.

Want to learn more about using a Map object in TypeScript? Check out these resources: How to Iterate over a Map in TypeScript,Define a Map with Array values in TypeScript.

# Declaring an empty typed Map in TypeScript

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);

declaring empty typed map in typescript

The code for this article is available on GitHub

The code sample declares an empty, typed Map that has string keys and arrays containing strings as values.

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.

Copyright ยฉ 2024 Borislav Hadzhiev