Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.
A map in TypeScript is a built-in object that stores key-value pairs.
Maps remember the original insertion order of the keys. So, iterating over it returns the keys in the order they were added.
Here's a quick example of maps. You can read the rest of the tutorial to learn more.
Example
let idStudents: Map<number, string> = new Map();
// Add elements
idStudents.set(1, "Luke");
idStudents.set(2, "Leia");
console.log(idStudents);
// Output: Map(2) { 1 => 'Luke', 2 => 'Leia' }
Here, idStudents is a map that stores number keys and string values. We then used the set() method to add the key-value pairs to the map.
Create TypeScript Map
To create a Map, you can use the new Map() constructor. For example,
// Create an empty map 
let scores: Map<string, number> = new Map();
console.log(scores);
Output
Map(0) {}
Here, scores is an empty map with no elements yet.
Insert Item to Map
After we create an empty map, you can use the set() method to insert elements into it. For example,
let scores: Map<string, number> = new Map();
// Add elements
scores.set("Alice", 85);
scores.set("Bob", 92);
console.log(scores);
Output
Map(2) { 'Alice' => 85, 'Bob' => 92 }
Here, we added two entries to the scores map.
Map with Object or Function Keys
In TypeScript, you can use any type of object or function as a key in a map, just like in JavaScript. For example,
// Create an empty Map
let map = new Map<object, object>();
// Create an object to use as key
let obj = {};
// Insert an object as key-value pair
map.set(obj, { name: "John", age: 27 });
// Get the value using the object key
console.log(map.get(obj));
Output
{ name: 'John', age: 27 }
Here, we have used object obj as a key with value {name: "John", age: 27}. We can retrieve the value associated with the object key as: map.get(obj).
Map Operations
1. Access Map Elements
To access Map elements, you can use the get() method. For example,
let studentInfo = new Map<string, string>();
studentInfo.set("name", "Jack");
// Access value of the "name" key
let result = studentInfo.get("name");
console.log(result);
Output
Jack
Here, studentInfo.get("name") retrieves the value of the name key.
2. Check Map Elements
You can use the has() method to check if the element is in a map. For example,
let map1 = new Map<string, object>();
map1.set('info', { name: 'Jack', age: 26 });
// Check if 'info' key exists in the map
console.log(map1.has('info')); // true
In this example, if the key exists, has() returns true. Otherwise, it returns false.
3. Delete Map Elements
To delete a map element, you can use the delete() method. The delete() method returns:
true- if a specified key/value pair exists and has been removedfalse- if the element does not exist
For example,
let studentInfo = new Map<string, string>();
studentInfo.set("name", "Jack");
studentInfo.set("subject", "Biology");
console.log("Before deletion:", studentInfo);
// Delete the "subject" key
let wasDeleted = studentInfo.delete("subject");
// Check if the deletion was successful
console.log(wasDeleted); // true
console.log("After deletion:", studentInfo);
Output
Before deletion: Map(2) { 'name' => 'Jack', 'subject' => 'Biology' }
true
After deletion: Map(1) { 'name' => 'Jack' }
Here, we have used the delete() method to delete the subject key from the studentInfo map. 
Notice that the value of the wasDeleted variable is true since the subject/Biology pair has been removed. 
The clear() Method
You can use the clear() method if you want to remove all the key/value pairs from a Map object. For example,
let studentInfo = new Map<string, string>();
studentInfo.set("name", "Jack");
studentInfo.set("subject", "Biology");
// Remove all elements
studentInfo.clear();
console.log(studentInfo);
Output
Map(0) {}
Iterate Through a Map
You can iterate through Map elements using the for...of loop. For example,
let studentInfo: Map<string, string | number> = new Map();
studentInfo.set("name", "Jack");
studentInfo.set("score", 98);
studentInfo.set("subject", "Biology");
// Iterate over entries using for...of
for (let [key, value] of studentInfo) {
    console.log(`${key}: ${value}`);
}
Output
name: Jack score: 98 subject: Biology
Other Ways to Iterate Through a Map
You can also use the forEach() method to iterate over Map elements. For example,
let studentInfo: Map<string, string | number> = new Map();
studentInfo.set("name", "Jack");
studentInfo.set("score", 98);
studentInfo.set("subject", "Biology");
// Iterate over the map using forEach
studentInfo.forEach((value, key) => {
    console.log(`${key}: ${value}`);
});
Output
name: Jack score: 98 subject: Biology
You can iterate over Map and get the key using the keys() method. For example,
let studentInfo: Map<string, string | number> = new Map();
studentInfo.set("name", "Jack");
studentInfo.set("score", 98);
studentInfo.set("subject", "Biology");
// Get all keys using keys()
for (let key of studentInfo.keys()) {
    console.log(key);
}
Output
name score subject
You can iterate over a Map and get the values using the values() method. For example,
let studentInfo: Map<string, string | number> = new Map();
studentInfo.set("name", "Jack");
studentInfo.set("score", 98);
studentInfo.set("subject", "Biology");
// Get all values using values()
for (let value of studentInfo.values()) {
    console.log(value);
}
Output
Jack 98 Biology
Map Methods
TypeScript provides various built-in Map methods to perform useful operations. Some of them are:
| Methods | Description | 
|---|---|
set(key,value) | 
Adds a new key-value pair to the map | 
get(key) | 
Returns the value associated with a key | 
delete(key)  | 
Removes a key-value pair by key | 
clear() | 
Removes all key-value pairs from the map | 
has(key) | 
Returns a boolean indicating whether a key exists in the map | 
entries() | 
Returns a new map iterator object that contains the key-value pairs for each element | 
We have used most of the methods till now. Now, let's look at the example below that illustrates the use of the entries() and the has() methods.
// Create a Map with string keys and string values
let map: Map<string, string> = new Map();
// Add elements using set()
map.set("food", "pizza");
map.set("price", "$50");
// Use has() to check if the 'food' key exists
console.log(map.has("food")); // true
// Iterate over entries 
for (let [key, value] of map.entries()) {
    console.log(`${key}: ${value}`);
}
Output
true food: pizza price: $50
Here,
map.has("food")- returns true because the keyfoodexists in the mapmap.entries()- iterates over all entries in the map, displaying each key and its associated value
TypeScript WeakMap
The WeakMap is similar to a Map. However, WeakMap can only contain objects as keys. For example,
let weakMap: WeakMap<object, string> = new WeakMap();
console.log(weakMap);
let obj = {};
// Adding object (element) to WeakMap
weakMap.set(obj, 'hello');
console.log(weakMap); 
WeakMaps and Other Types
When you try to add other data types besides objects, WeakMap throws an error. For example,
let weakMap: WeakMap<object, string> = new WeakMap();
// Adding string "obj" as a key to WeakMap
weakMap.set("obj", "hello");
This throws a TypeError at runtime, because WeakMap only accepts objects as keys.
WeakMap Methods
TypeScript provides various built-in WeakMap methods such as:
| Methods | Description | 
|---|---|
get(key) | 
Retrieves the value associated with the key from the WeakMap. | 
set(key, value) | 
Adds a new key-value pair associated with the WeakMap. | 
delete(key) | 
Removes the key-value pair associated with the key. | 
has(key) | 
Checks whether the WeakMap contains the specified key. | 
Example: WeakMap Methods
let weakMap: WeakMap<object, string> = new WeakMap();
let obj = {};
// Use set() to add an object (element) to WeakMap
weakMap.set(obj, "hello");
console.log(weakMap); // WeakMap { <items unknown> }
// Use get() to get the element of a WeakMap 
console.log(weakMap.get(obj)); // hello
// Use has() to check if an element is present in WeakMap
console.log(weakMap.has(obj)); // true
// Use delete() to delete the element of WeakMap
console.log(weakMap.delete(obj)); // true
console.log(weakMap); // WeakMap { <items unknown> }
Here,
set(obj, "hello")- adds the objectobjas a key and with value"hello"in the WeakMap.get(obj)- retrieves the value ("hello") associated with the keyobjfrom the WeakMap.has(obj)- checks if the keyobjis present in the WeakMap, returningtruebecause it existsdelete(obj)- removes the key-value pair whereobjis the key from the WeakMap, returningtrueto indicate successful deletion.
Note: WeakMap is supported in all modern browsers, but its contents are intentionally hidden and it is not iterable. If you are targeting very old browsers (like IE11 or earlier), check compatibility before using.
More on Maps and WeakMaps
You can get the number of elements in a map using the size property. For example,
let countryInfo: Map<string, string> = new Map();
countryInfo.set("countryName", "Japan");
// Check size of the map
console.log(countryInfo.size); // 1
Unlike maps, WeakMaps are not iterable. This means you cannot use loops like for...of to iterate over a WeakMap. For example,
let weakMap: WeakMap<object, string> = new WeakMap();
console.log(weakMap);
let obj = {};
weakMap.set(obj, "hello");
console.log(weakMap);
// Attempt to iterate
// Throws an error
for (let item of weakMap) {
    console.log(item);
}
This will throw a TypeError because WeakMap is not iterable.
| Map | WeakMap | 
|---|---|
Map can use any type of value as keys, including objects and primitives. | 
WeakMap can only use objects as keys. | 
Map is fully iterable, allowing access to its elements through methods like keys(), values(), and entries(). | 
WeakMap is not iterable. | 
In Map, keys and values are strongly referenced, meaning they are not garbage collected as long as the Map itself is alive.  | 
WeakMap allows keys to be garbage collected if there are no other references to them. | 
Also Read: