How to create a Map in TypeScript
Overview
We use the Map as a data structure to store key-value entries. It is also known as a dictionary. In TypeScript, we can easily create a Map using the new keyword and provide the data types for keys and values.
Syntax
// empty mapnew Map<type, type>()// initialized mapnew Map<type, type>([[keyN, valueN]])
Syntax for creating a Map in TypeScript
Parameter
type: This is the specified data type for the keys and values that will be added to the dictionary. It is usually astring,number,null, etc.keyN: This represents a key that is added to the dictionary. It could be one or more.valueN: This is the value for any key added to the dictionary. We can have more than one value in a Map, each with its own keys.
Return value
A new Map is returned.
Example
// create some Mapslet evenNumbers = new Map<string, number>([["two", 2], ["four", 4], ["eight", 8]])let cart = new Map<string, number>([["rice", 500], ["bag", 10]])let countries = new Map<string, string>([["NG", "Nigeria"], ["BR", "Brazil"], ["IN", "India"]])let isMarried = new Map<string, boolean>([["James", false], ["Jane", true], ["Doe", false]])let emptyMap = new Map<null, null>()// logout the mapsconsole.log(evenNumbers)console.log(cart)console.log(countries)console.log(isMarried)console.log(emptyMap)
Explanation
- Line 2–6: We create some maps in
TypeScriptby providing different data types for keys and values, and different number of key-value pairs. - Line 9–13: We log out the maps and print them to the console.