What is map.get() method in TypeScript?
Overview
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.
Syntax
Map.get(key)
The syntax for the get() method of a map in TypeScript
Parameters
Map: This is the map whose key's value we want to get.
key: This is the key whose value we want to get.
Return value
If the specified key exists, then the value is returned. Otherwise, undefined 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>()// 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
Explanation
- Lines 2–6: We create some maps.
- Lines 9–13: We use the
getmethod to get the values of the keys specified for each map. Then, we log the results to the console.