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.
// empty map new Map<type, type>() // initialized map new Map<type, type>([[keyN, valueN]])
type
: This is the specified data type for the keys and values that will be added to the dictionary. It is usually a string
, 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. A new Map
is returned.
// create some Maps let 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 maps console.log(evenNumbers) console.log(cart) console.log(countries) console.log(isMarried) console.log(emptyMap)
TypeScript
by providing different data types for keys and values, and different number of key-value pairs.RELATED TAGS
CONTRIBUTOR
View all Courses