What is the map.keys() method in TypeScript?

Overview

A map, also known as a dictionary, is a data structure that is made up of key-value pairs. Each entry of the map contains a key-value pair. We can use the keys() method to get all the keys of the map.

Syntax

Map.keys()
The syntax for map.keys() in TypeScript

Parameters

Map: This is the set whose keys' iterators we want to get.

Return value

It returns a Map iterator.

Example

// 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>()
// get the iterators
let itr1 = evenNumbers.keys()
let itr2 = cart.keys()
let itr3 = countries.keys()
let itr4 = isMarried.keys()
let itr5 = emptyMap.keys()
// log out the iterators
console.log(itr1)
console.log(itr2)
console.log(itr3)
console.log(itr4)
console.log(itr5)
// log out values for any of the iterators
for (let value of itr1) {
console.log(value);
}

Explanation

  • Lines 2–6: We create some maps in TypeScript.
  • Lines 9–13: We use the keys() method to get the iterators of the created sets.
  • Lines 16–20: We log the iterators to the console.
  • Lines 23-25: We use the for of loop to iterate over one of the iterators. Next, we print its values to the console.

Free Resources