A map is made up of key-value pairs. Sometimes, it is referred to as a dictionary.
We can use the set()
method of Map
in TypeScript to add entries to a map. To add entries, we simply provide the key-value pair we want to add.
Map.set(key, value)
Note:
Map
will be replaced with the name of the name of theMap
object we use.
key
, value
: This is the pair we want to add to the map, since a map is made up of key-value pairs. These can be of any data type.This method returns a new map with the key-value pair inserted into it.
Let's look at an example of maps.
// 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>()// Add entries using the set methodevenNumbers.set("twenty", 20)cart.set("vodka", 50)countries.set("IR", "Iran")isMarried.set("Emeka", true)emptyMap.set(null, null)// Print out the mapsconsole.log(evenNumbers)console.log(cart)console.log(countries)console.log(isMarried)console.log(emptyMap)
set()
method to add some entries to the maps we created.