Map Typescript Example with Explanations

 Map Typescript Example with Explanations

Question: Can you provide an example of using maps in TypeScript with explanations?

Answer:

Certainly! In TypeScript, a Map is a collection of key-value pairs where each key and value can be of any data type. Here's an example with explanations:

typescript
// Creating a new Map
let myMap = new Map();

// Adding key-value pairs to the Map
myMap.set("name", "John");
myMap.set("age", 25);
myMap.set("isStudent", true);

// Accessing values using keys
console.log(myMap.get("name")); // Output: John
console.log(myMap.get("age")); // Output: 25
console.log(myMap.get("isStudent")); // Output: true

// Checking if a key exists in the Map
console.log(myMap.has("name")); // Output: true
console.log(myMap.has("gender")); // Output: false

// Deleting a key-value pair from the Map
myMap.delete("age");

// Iterating through the Map using forEach
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});

/*
Output:
name: John
isStudent: true
*/

// Checking the size of the Map
console.log(myMap.size); // Output: 2 

Explanation:

  1. Creating a Map:

    • We create a new Map using the Map constructor: let myMap = new Map();
  2. Adding key-value pairs:

    • We use the set method to add key-value pairs to the Map.
  3. Accessing values:

    • The get method is used to retrieve the value associated with a specific key.
  4. Checking key existence:

    • The has method is used to check if a key exists in the Map.
  5. Deleting key-value pairs:

    • The delete method removes a key-value pair based on the provided key.
  6. Iterating through the Map:

    • We use the forEach method to iterate over the key-value pairs in the Map.
  7. Checking the size:

    • The size property gives the number of key-value pairs in the Map.

This example demonstrates the basic operations you can perform with a Map in TypeScript. Maps are versatile and provide an efficient way to manage key-value data.

একটি মন্তব্য পোস্ট করুন

0 মন্তব্যসমূহ