TypeScript Map: A Complete Tutorial With Examples

Understanding TypeScript Map

A TypeScript map is an object that stores pairs of keys and values, and it keeps track of the order in which the keys were added.

You can use any type of value, whether it’s an object or a primitive value, as a key or a value.

Moreover, a map is a feature added in ES6 so that you can use it in both JavaScript and TypeScript. It lets you store pairs of keys and values.

What are the Common Operations Available in TypeScript Map?

The following are the common operations that you can utilize in TypeScript Map.

OperationDescription
map.set (key, value)This operation adds a pair of key and value to the Map.
map.get (key)This operation gets or retrieves the value for a key from the Map.
map.has(key)This operation checks if a key is in the Map. It returns true or false.
map.sizeThis operation shows how many entries are in the Map.
map.delete(key)This operation removes a key-value pair by its key. If the key is found and removed, it returns true, otherwise it returns false.
map.clear()This operation removes all entries from the Map.

How to Create a Map?

To create a map in TypreScript is pretty simple, just create a new Map object.

For instance:

let sampleMap = new Map<string, number>();

To set up a Map with starting key-value pairs, give the pairs as an array when you’re making the Map.

let’s take a look at the example:

let SampleMap = new Map<string, string>([
        ["key1", "value1"],
        ["key2", "value2"]
    ]);

How to Add Entries from the Map?

You can add or insert pairs of keys and values into the map with the set() method.

If the key is already on the map, this will update its value.

Here’s an example:

let SampleMap: Map<number, string> = new Map();

// Add entries to the Map
SampleMap.set(1, 'Programming');
SampleMap.set(2, 'Software Development');
SampleMap.set(3, 'Web Development');
console.log(SampleMap);

Output:


Map (3) {1 => "Programming", 2 => "Software Development", 3 => "Web Development"} 

How to Get or Retrieve Entries from the Map?

To get or retrieve a value in the map by using the get() method and providing the key.

Here’s an example:

// Create a new Map
let SampleMap: Map<number, string> = new Map();

// Add an entry to the Map
SampleMap.set(1, 'Programming');
SampleMap.set(2, 'Software Development');
SampleMap.set(3, 'Web Development');

// Retrieve the entry from the Map
let value = SampleMap.get(1); 

console.log(value);

Output:

"Programming" 

How to Delete Entries from the Map?

To delete a key-value pair from the map with the delete() method.

It returns true if the key was in the map and was removed, and false otherwise.

For example:

// Create a new Map
let SampleMap: Map<number, string> = new Map();

// Add an entry to the Map
SampleMap.set(1, 'Programming');
SampleMap.set(2, 'Software Development');
SampleMap.set(3, 'Web Development');

// Delete the entry from the Map
SampleMap.delete(1); // deletes the entry with key 1

console.log(SampleMap.has(1)); // logs false, because the entry has been deleted

Output:

false 

Here’s an example:

// Create a new Map
let SampleMap: Map<number, string> = new Map();

// Add an entry to the Map
SampleMap.set(1, 'Programming');
SampleMap.set(2, 'Software Development');
SampleMap.set(3, 'Web Development');

// Delete the entry from the Map
SampleMap.delete(1); // deletes the entry with key 1

console.log(SampleMap); 

Map (2) {2 => "Software Development", 3 => "Web Development"} 

How to Check if a Key Exists in a Map?

To check if a key exists in a Map in TypeScript using the has() method.

Here’s an example:

// Create a new Map
let SampleMap: Map<number, string> = new Map();

// Add an entry to the Map
SampleMap.set(1, 'Programming');
SampleMap.set(2, 'Software Development');
SampleMap.set(3, 'Web Development');

// Check if a key exists in the Map
let exists = SampleMap.has(1); // returns true

console.log(exists); // logs true

Output:

true

How to Iterate over a Map?

There are several ways to iterate over a Map in TypeScript:

1. forEach() method

The forEach() method lets you run a function for each pair of key and value in the Map.

let SampleMap: Map<number, string> = new Map();
SampleMap.set(1, 'Programming');
SampleMap.set(2, 'Software Development');
SampleMap.set(3, 'Web Development');

SampleMap.forEach((value, key) => {
    console.log(`Key: ${key}, Value: ${value}`);
});

2. for…of loop:

You can also use a for…of loop to go through a Map in TypeScript.

let mapExample: Map = new Map();
mapExample.set(1, 'Programming');
mapExample.set(2, 'Software Development');
mapExample.set(3, 'Web Development');

for (const [key, value] of mapExample) {
console.log(Key: ${key}, Value: ${value});
}

3. Going through keys or values:

The keys() and values() methods give you objects that you can iterate over, which contain the keys and values of the Map.

let SampleMap: Map<number, string> = new Map();
SampleMap.set(1, 'Programming');
SampleMap.set(2, 'Software Development');
SampleMap.set(3, 'Web Development');

for (const key of SampleMap.keys()) {
    console.log(`Key: ${key}`);
}

for (const value of SampleMap.values()) {
    console.log(`Value: ${value}`);
}

Conclusion

Now you fully understand how to utilize TypeScript Map which offers numerous functionalities for managing key-value pairs.

A Map can store any type of value as keys or values, preserving the insertion order.

This article also discusses the common operations including adding, retrieving, checking, and deleting entries, as well as iterating over the Map.

I hope this article has helped you understand the TypeScript Map.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment