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:
-
KeyType
: The data type of the keys in the map. -
ValueType
: The data type of the values associated with the keys in the map.
Common Methods and Properties:
-
set(key: KeyType, value: ValueType): Map<KeyType, ValueType>
- Adds or updates a key-value pair in the map.
- Returns the updated map.
-
get(key: KeyType): ValueType | undefined
- Retrieves the value associated with the specified key.
-
Returns
undefined
if the key is not found.
-
has(key: KeyType): boolean
- Checks if the map contains the specified key.
-
Returns
true
if the key is found; otherwise,false
.
-
delete(key: KeyType): boolean
- Removes the key-value pair associated with the specified key.
-
Returns
true
if the key was found and removed; otherwise,false
.
-
clear(): void
- Removes all key-value pairs from the map.
-
forEach(callbackfn: (value: ValueType, key: KeyType, map: Map<KeyType, ValueType>) => void, thisArg?: any): void
- Calls a provided function once for each key-value pair in the map, in insertion order.
-
size: number
- Returns the number of key-value pairs in 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: 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