AppDividend
Latest Code Tutorials

TypeScript Map: A Complete Guide

0

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. In the TypeScript map, we can use any value either as a key or as a value.

Understanding TypeScript map

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.

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. The keys aren’t limited to strings, numbers, and symbols.
  2. The map is a collection, meaning it has a size, an order, and can be iterated over.
  3. The maps are designed to deal with optional keys instead of with required keys. 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 map, use 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

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

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 in the map.
2. map.get(key) The map.get() method is used to retrieve 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 is used to returns the size of the map.
6. map.clear() The map.clear() method removes everything from the map.

 

TypeScript map complete 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, first, we have defined 4 key-value pairs and then used different methods to get the values, check if the key exists in the map, the size of the map, and remove the key from the map.

How to iterate Map Data in TypeScript

We can iterate either map keys or map values in TypeScript.

To iterate map keys or map values in TypeScript, use ‘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 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, there would be an ICollection interface that forces all collection to be consistent (for both builtin 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.

See also

TypeScript enum

TypeScript interface

Leave A Reply

Your email address will not be published.

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