Here’s a rewritten version of the article:

Unlocking the Power of Maps in TypeScript

When it comes to storing and managing data in TypeScript, maps are an essential tool to have in your toolkit. A map is a built-in object that stores key-value pairs, remembering the original insertion order of the keys. This means that when you iterate over a map, the keys are returned in the order they were added.

Creating a Map

To create a map, you can use the new Map() constructor. For instance:


let scores = new Map();

This creates an empty map with no elements yet.

Inserting Items into a Map

After creating an empty map, you can use the set() method to insert elements into it. For example:


scores.set("John", 80);
scores.set("Jane", 90);

This adds two entries to the scores map.

Map Operations

Accessing Map Elements

You can use the get() method to access the value associated with a specific key. For instance:

let studentInfo = new Map();
studentInfo.set("name", "John");
studentInfo.set("age", 27);

console.log(studentInfo.get("name")); // Output: John

Checking Map Elements

The has() method allows you to check if a key exists in a map. For example:


console.log(studentInfo.has("name")); // Output: true

Deleting Map Elements

You can use the delete() method to remove a key-value pair from a map. For instance:


studentInfo.delete("subject");
console.log(studentInfo.has("subject")); // Output: false

Iterating Through a Map

You can iterate through a map using the for...of loop or the forEach() method. For example:


for (let [key, value] of studentInfo) {
console.log(
${key}: ${value}`);
}

studentInfo.forEach((value, key) => {
console.log(${key}: ${value});
});
“`

Map Methods

TypeScript provides various built-in map methods, including clear(), entries(), keys(), and values(). These methods allow you to perform useful operations on your maps.

TypeScript WeakMap

A WeakMap is similar to a Map, but it can only contain objects as keys. For instance:


let weakMap = new WeakMap();
let obj = { name: "John", age: 27 };
weakMap.set(obj, "hello");

WeakMaps have methods like get(), set(), delete(), and has(). However, unlike Maps, WeakMaps are not iterable, and their contents are intentionally hidden.

More on Maps and WeakMaps

You can get the number of elements in a map using the size property. For example:


console.log(studentInfo.size); // Output: 2

Remember that WeakMaps are not iterable, so you cannot use loops like for...of to iterate over them.

Leave a Reply