We use the get()
method of a map in TypeScript to get the value for a key in a map. A map is a key-value pair data structure.
Map.get(key)
Map
: This is the map whose key's value we want to get.
key
: This is the key whose value we want to get.
If the specified key exists, then the value is returned. Otherwise, undefined
is returned.
// 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>()// get some valuesconsole.log(evenNumbers.get("two")) // 2console.log(cart.get("books")) // undefinedconsole.log(countries.get("IN")) // Indiaconsole.log(isMarried.get("James")) // falseconsole.log(emptyMap.get(null)) // undefined
get
method to get the values of the keys specified for each map. Then, we log the results to the console.