“Maps” are used for storing and retrieving key-value pairs. It is a built-in data structure in TypeScript that is similar to a JavaScript map but it has the added benefit of type-checking. The TypeScript Map class provides a type-safe way to store key-value pairs with any type of key and value.
This blog will explain the ways to create a Map in TypeScript.
How to Create a Map in TypeScript?
For creating a map in TypeScript, use the following approaches:
Method 1: Create a Map Using the “Map” Constructor
For creating a map in TypeScript, use the “Map” constructor. While using the “Map” constructor there are two ways to create a map in TypeScript:
-
- Either you can declare the map with the “new” keyword and then use the “set()” method to add the key-value pairs.
- Or initialize the map with key-value pairs at the time of declaration.
Syntax
The given syntax is utilized for creating a map in TypeScript using the Map constructor:
let map = new Map<string, number>();
Here, the “string”, and “number” is the type of key and value of the map.
To initialize the map at the time of declaration, use the following syntax:
["key1", "value1"],
["key2", "value2"]
]);
Example 1:
Create a map using the Map constructor by defining the type for the key and value of the map:
Use the “set()” method for adding the key-value pairs in the map:
marks.set('Geography', 25);
marks.set('Maths', 40);
marks.set('English', 31);
Finally, print the map on the console:
Now, transpile the TypeScript code to the JavaScript code by executing the below-given command on the terminal:
Then, execute the JavaScript code using the following command:
Output
Note: It is mandatory to transpile the TypeScript file after updating the TypeScript code.
Example 2:
You can also initialize the map using the Map constructor:
["History", "39"],
["Geography", "25"],
["Maths", "40"],
["English", "31"]
]);
Print the map on the console using the “console.log()” method:
Output
Method 2: Create a Map Using the “Record Utility” Type
Another way to create a map is to use the “Record utility” type. It is a built-in type in TypeScript that can be utilized for defining a type that represents a map of key-value pairs. It takes two parameters, the type of the keys, and the type of the values.
Syntax
Follow the given syntax for creating Map using the “Record Utility” Type:
Example
Create a map using the “Record Utility Type”:
Assign the value to the keys of the map:
marks['Geography'] = '25';
marks['Maths'] = '40';
marks['English'] = '31';
Lastly, print the map on the console:
Output
We have provided all the necessary information relevant to creating a Map on TypeScript.
Conclusion
There are two ways to create a map in TypeScript such as using the “Map Constructor” and using the “Record utility type”. Both approaches perform well but the first approach is the common way to create a map in TypeScript. This blog explained the ways to create a Map in TypeScript.