TypeScript Dictionary Type

The TypeScript dictionary type allows you to store data in a key-value format. TypeScript provides the dictionary functionality through the Map data type. In this post, we will learn about TypeScript Dictionary Type (Map) with multiple examples.

Introduction

The map data type allows you to store data in key-value pairs. Key-value pairs offer a faster way to access the data because we are using keys to access the data directly. In comparison to Arrays in TypeScript, where we need to use indexers to access the data, and we need to traverse all the data using a for loop to check if the data exists or not. But in dictionary data types, we access the data directly using keys to check if it exists or not.

TypeScript provides two types of dictionary types:

  1. Non-generic Dictionary
  2. Generic Dictionary

Non-generic Dictionary

In the non-generic dictionary, TypeScript assumes key and value both as any data type. So, we can store any type of data in the dictionary.

The map object provides the set and get functions to store and retrieve the data from the dictionary.

Below is an example of a non-generic dictionary type in TypeScript.

let map = new Map();

map.set("key1", "value 1");
map.set(1, 9899);
map.set(2, "test234");

console.log(map.get("key1"));
console.log(map.get(1))
console.log(map.get(2));

Result
------
"value1"
9899
"test234"

In the above example, I have declared a Map object in the first line. I have used the set method to store multiple key-value pairs. The get method is used to retrieve data from the dictionary.

Generic Dictionary

A generic dictionary allows you to store key-value pairs in a type-safe way. When we are declaring a map variable, we also specify allowed data types in both key and value. This will ensure that the user can pass only valid data. Below is an example.

Dictionary Type Declaration

let mapObj = new Map<string, number>();

In the above declaration, we declared a new Map object. The first generic parameter is the data type of key, and the second parameter is the value data type. We can only store string data as a key and integer data as a value.

We can also initialize the data during the declaration. Below is an example.

let mapObj = new Map<string, number>(
    [
        ["key1", 1],
        ["key2", 2],
        ["key3", 3],
    ]);

Add Data

To add data to a dictionary, we can use the set method of the map data type. The set method takes two parameters. The first parameter is for a key, and the second parameter is for a value.

let mapObj = new Map<string, number>();

mapObj.set("key1", 1);
mapObj.set("key2", 2);
mapObj.set("key3", 3);

Retrieve Data

To retrieve the data based on the key from dictionary, we can use the get method. In get method, we can pass the key as parameter and it will return the value.

console.log(mapObj.get("key1"));

Result
------
1

If key is not found, then get method will return undefined.

For each loop: Retrieve all entries

To get all the values from dictionary, we can iterate over the dictionary using for each loops. Below are the functions supported.

  1. keys(): Return all keys
  2. values(): Returns all values
  3. entries(): Return entry as key-value pair

All above functions return iterator objects which we can use in for each loop.

Below are the examples of each method.

for (let key of mapObj.keys()) {
    console.log(key, "=>", mapObj.get(key));
}

for (let value of mapObj.values()) {
    console.log("value: ", value);
}

for (let [key, value] of mapObj.entries()) {
    console.log(key, "=>", value);
}

Check Key Exists or Not

To check where key exists in a dictionary or not, use the has method of Map object. The has method takes key as parameter and return boolean value true if key exists and false value if key does not exist.

if (mapObj.has("key1")) {
    console.log("key exists");
} else {
    console.log("key does not exists");
}

Delete Key and Clear all Keys

To delete a particular key, use delete method and for clear all the values in the dictionary use clear method.

mapObj.delete("key2");

console.log(mapObj.has("key2")); //Returns false

mapObj.clear(); //delete all keys, values

Using Interface Object as Value in Dictionary

We can also store interface object as value in the dictionary. Below is an example.

interface IPerson {
    id: number;
    name: string;
    age: number;
    isEnabled: boolean;
}

let person1: IPerson = { id: 1, name: "ram", age: 32, isEnabled: false};
let person2: IPerson = { id: 2, name: "shyam", age: 39, isEnabled: true};

let mapObj = new Map<string, IPerson>();
mapObj.set(person1.name, person1);
mapObj.set(person2.name, person2);

for (let key of mapObj.keys()) {
    console.log(mapObj.get(key));
}

Result
------
{
  "id": 1,
  "name": "ram",
  "age": 32,
  "isEnabled": false
} 
{
  "id": 2,
  "name": "shyam",
  "age": 39,
  "isEnabled": true
} 

I have declared an interface IPerson. After that, I have declared two objects, person1 and person2. Created new map object, where I store object name property as keys. In the end, I retrieved all objects in the dictionary using for loop.

Dictionary Functions List

Function NameDescription
set(key, value)Store data into dictionary
get(key)Get value from dictionary
has(key)Check key exists or not
keys()Returns an iterator object for keys
values()Returns an iterator object for values
entries()Returns an iterator object for key-values
delete(key)Delete entry of key-value pair from dictionary
clear()Delete all entries
size()Returns count of entries
Map Dictionary Functions Table

Summary

TypeScript dictionary type (Map) supports key-value pair storage. It offers faster data access as compared to arrays. TypeScript supports both non-generic and generic dictionary.