Open In App

TypeScript Map

TypeScript Map is a built-in data structure that allows you to store key-value pairs and remembers the original insertion order of the keys similar to other programming languages where keys and values can be of any data type.

Syntax:

let myMap = new Map<KeyType, ValueType>();

Parameters:

Common Methods and Properties:

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: In this example, we are using the forEach method to Iterate over map data:




let myMap = new Map<string, number>();
 
myMap.set("one", 1);
myMap.set("two", 2);
myMap.set("three", 3);
 
// Using forEach method
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: In this example, KeyType is string, and ValueType is number. The methods demonstrate common operations on a TypeScript Map.




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.size); // Output: 1
 
myMap.forEach((value, key) => {
    console.log(`Key: ${key}, Value: ${value}`);
});

Output:

1
true
1
Key: one, Value: 1

Article Tags :