Maps

In TypeScript, a map is a collection of key-value pairs that can be used to store and retrieve data. Maps are similar to arrays, but instead of using a numeric index to access values, maps use keys to access values.

In TypeScript, maps can be implemented using the built-in Map type. Here’s an example of how to define and use a map in TypeScript:

const myMap = new Map<string, number>();

myMap.set("foo", 1);
myMap.set("bar", 2);


console.log(myMap.get("foo"));

console.log(myMap.has("baz"));

console.log(myMap.delete("foo"));

for (const [key, value] of myMap.entries()) {
  console.log(`${key}: ${value}`);
}

In the above example, we define a map with string keys and number values using the Map<string, number> syntax. We then add key-value pairs to the map using the set method, and retrieve a value from the map using the get method. We also check if a key exists in the map using the has method, remove a key-value pair from the myMap.

Example

// Define the type for the keys and values of the map
type MyKeyType = string;
type MyValueType = number;

// Define the map using the types for keys and values
const myMap: Map<MyKeyType, MyValueType> = new Map();

// Add entries to the map
myMap.set("one", 1);
myMap.set("two", 2);
myMap.set("three", 3);

// Access the values in the map
console.log(myMap.get("one"));
console.log(myMap.get("two"));
console.log(myMap.get("three"));

// Loop through the entries in the map
for (const [key, value] of myMap.entries()) {
  console.log(`${key}: ${value}`);
}

In this example, MyKeyType is a type alias for the key type of the map, which is string. MyValueType is a type alias for the value type of the map, which is number.

You can also use other types for the keys and values of the map, depending on your needs.

typescript programming map

Subscribe For More Content