Open In App

TypeScript Map

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript Map is a collection that stores key-value pairs, where keys can be of any type. It maintains the insertion order of keys and provides methods to add, retrieve, check, remove, and clear entries, ensuring efficient management of key-value data.

Creating a Map

A map can be created as:

let myMap = new Map();

Map Methods

Map Methods

Description

map.set(key,value)

Used to add entries in the map.

map.get(key)

Used to access entries from the map. Returns undefined if the key does not exist in the map.

map.has(key)

Returns true if the key is present in the map.

map.delete(key)

Used to remove entries by key in the map.

map.size()

Used to return the size of the map.

map.clear()

Removes everything from the map.

Iterating Map Data

Iterating over the key-value pairs in a TypeScript Map can be done using various methods. The forEach the method is commonly used for this purpose.

Example 1: Using the forEach Method

In this example, we are using the forEach method to Iterate over map data:

JavaScript
let myMap = new Map<string, number>();
myMap.set('one', 1);
myMap.set('two', 2);
myMap.set('three', 3);

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

Output:

Key: one, Value: 1
Key: two, Value: 2
Key: three, Value: 3

Example 2: Common Operations on a TypeScript Map

In this example, KeyType is string, and ValueType is number. The methods demonstrate common operations on a TypeScript Map.

JavaScript
let myMap = new Map<string, number>();
myMap.set('one', 1);
myMap.set('two', 2);

console.log(myMap.get('one')); // Output: 1
console.log(myMap.has('two')); // Output: true

myMap.delete('two');
console.log(myMap.get('two')); // Output: undefined

console.log(`Size: ${myMap.size}`); // Output: Size: 1

myMap.clear();
console.log(`Size after clear: ${myMap.size}`); // Output: Size after clear: 0

myMap.set('one', 1);
myMap.forEach((value, key) => {
  console.log(`Key: ${key}, Value: ${value}`);
});

Output:

1
true
undefined
Size: 1
Size after clear: 0
Key: one, Value: 1

Next Article

Similar Reads