Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript

How to create a Map in TypeScript

Theodore Kelechukwu Onyejiaku

Overview

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.

Syntax

// empty map
new Map<type, type>()
// initialized map
new Map<type, type>([[keyN, valueN]])
Syntax for creating a Map in TypeScript

Parameter

  • 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.

Return value

A new Map is returned.

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>()

// logout the maps
console.log(evenNumbers)
console.log(cart)
console.log(countries)
console.log(isMarried)
console.log(emptyMap)
Example to create Maps in TypeScript

Explanation

  • Line 2–6: We create some maps in TypeScript by providing different data types for keys and values, and different number of key-value pairs.
  • Line 9–13: We log out the maps and print them to the console.

RELATED TAGS

typescript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring