TypeScript Map: A Complete Guide

1
890
TypeScript Map - A Complete Guide

With ES6, Map and Set were introduced into JavaScript. They finally bring more sophisticated data structures to your web applications. Because of that, they are a very welcome addition to the language.  For too long, arrays have been forced to solve every single problem that is out there.

TypeScript map

TypeScript map is a new data structure that allows us to store data in the key-value pair and remembers the original insertion order of the keys. A map in TypeScript is a data structure that contains key-value pairs.

In this context, it is a bit like a JavaScript Object, but there are some significant differences:

  1. First, the keys aren’t limited to Strings, Numbers, and Symbols.
  2. The map is a collection, meaning it has a size and order and can be iterated.
  3. The maps are designed to deal with optional keys instead of required ones. This is more important when using TypeScript and ensuring type safety.

How to create a Map in TypeScript

To create a map in TypeScript, use the following syntax.

let xmap = new Map();

To set a key value in the map, use the map.set() function.

// app.ts

let xmap = new Map();

xmap.set('name', 'Krunal');
console.log(xmap);

Go to the terminal where this file is and run the following command.

tsc --target es6 app.ts

If we don’t add the –target flag, we will get an error because it won’t be compatible with ES6. So, we have to add this flag to avoid any errors.

After running the command, you will see the new file is created called app.js and now run that file to get the output.

node app

Output

Map(1) { 'name' => 'Krunal' }

Map methods

No Methods Descriptions
1. map.set(key, value) The map.set() method is used to add entries to the map.
2. map.get(key) The map.get() method retrieves entries from the map. The get() method returns undefined if the key does not exist on the map.
3. map.has(key) The map.has() method returns true if the key is present in the map. Otherwise, it returns false.
4. map.delete(key) The map.delete() method is used to remove the entries by the key.
5. map.size() The map.size() method returns the map size.
6. map.clear() The map.clear() method removes everything from the map.

Example

Write the following code inside the app.ts file.

// app.ts

let xmap = new Map();

xmap.set('name', 'Krunal');
xmap.set('blog', 'https://appdividend.com');
xmap.set('boolean', true);
xmap.set('age', 27);

console.log("1st value: " + xmap.get('name'));
console.log("2nd value: " + xmap.get('blog'));
console.log("Key 'yes' is Present: " + xmap.has('yes'));
console.log("The size of Map is: " + xmap.size);
console.log("The deleted value: " + xmap.delete('boolean'));
console.log("The New Size is: " + xmap.size);

To run the file, type the following commands.

➜  es git:(master) ✗ tsc --target es6 app.ts
➜  es git:(master) ✗ node app
1st value: Krunal
2nd value: https://appdividend.com
Key 'yes' is Present: false
The size of Map is: 4
The deleted value: true
The New Size is: 3

In this example, we first defined 4 key-value pairs and then used different methods to get the values, check if the key exists in the map, the map size, and remove the key from the map.

How to iterate Map Data in TypeScript

To iterate map keys or values in TypeScript, use the “for…of” loop.

// app.ts

let xmap = new Map();

xmap.set('name', 'Krunal');
xmap.set('blog', 'https://appdividend.com');
xmap.set('boolean', true);
xmap.set('age', 27);

// Iterate over map keys  
console.log('Iterating keys: ')
for (let key of xmap.keys()) {
  console.log("Map Keys= " + key);
}

// Iterate over map values
console.log('----------------');
console.log('Iterating values: ')
for (let value of xmap.values()) {
  console.log("Map Values= " + value);
}

Output

➜  es git:(master) ✗ tsc --target es6 app.ts
➜  es git:(master) ✗ node app
Iterating keys:
Map Keys= name
Map Keys= blog
Map Keys= boolean
Map Keys= age
----------------
Iterating values:
Map Values= Krunal
Map Values= https://appdividend.com
Map Values= true
Map Values= 27

In this example, we have defined 4 pairs of maps, and first, we iterated keys using the map.keys() method, and then we iterated values using the map.values() method inside for…of loop.

To iterate and display the key and values of the map in a single loop, use the map.entries() method inside the for…of loop.

// app.ts

let xmap = new Map();

xmap.set('name', 'Krunal');
xmap.set('blog', 'https://appdividend.com');
xmap.set('boolean', true);
xmap.set('age', 27);

// Iterate over map entries  
console.log('Iterating Map Entries: ')
for (let entry of xmap.entries()) {
  console.log(entry[0] + ':', entry[1]);
}

Output

➜  es git:(master) ✗ tsc --target es6 app.ts
➜  es git:(master) ✗ node app
Iterating Map Entries:
name: Krunal
blog: https://appdividend.com
boolean: true
age: 27

You can see that we have displayed the data in key: value.

Conclusion

Set, Map and Array should all have comparable interfaces. Ideally, an ICollection interface would force all collections to be consistent (for both built-in and custom implementations).

The map is not the most used data structure in TypeScript or even in Javascript, but there are some instances where we can use this kind of data structure in our program to deal with specific types of data.

That’s it.

1 Comment

  1. This is a very useful article. I was trying to find information on the ES6 Map function and how to use it and this article explains everything very well.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.