{

How to create and declare dictionary in typescript


Typescript  Dictionary

Typescript dictionary class: Learn with examples.

In this Blog Post, Learn the dictionary in typescript with examples.

Dictionary is a type of data structure with unordered list data, that contains key and value values. It is the same as map type in typescript.

How to declare and initialize a dictionary using a map?

There are multiple ways can create a dictionary.

  • using map type A map is a type introduced inES6 and typescript. Following example contains
    • the declare and create a map variable
    • add the key-value pairs
    • check for key exists
    • get the value with a key
    • delete a key and its value
    • Iterate the map with keys and values
    • Remove all elements from a map
    • get the number of elements in a map
    • retrieve all keys and values with insertion order
let employees = new Map<string, string>();
employees.set("name", "john");

// Checking for the key exist :
employees.has("name"); // true

// get a value by a key:
employees.get("name"); // john

// delete an item by a key:
employees.delete("name");
// iterate key and values
employees.forEach((item, key) => console.log(item));

// remove all from map:
employees.clear();

// size:Number of elements in Map :
console.log(employees.size)

// get All keys with insertion order
let keys = Array.from(employees.keys());

// Extract values with insertion order
let values = Array.from(employees.values());

How to declare an interface for a dictionary?

Declare an interface using indexable type in typescript

declare an interface that accepts a key as a string and value of type T

interface Dictionary<T> {
    [Key: string]: T;
}

A class contains properties of the dictionary interface as below.

export class AllEmployees {
    employees: Dictionary<string> = {};
}

Dictionary interfaces declare with let keyword and initialize the values, add the values.

let emps: Dictionary<string> = {};
emps["name"] = "john";

How to declare a dictionary with record type

Record is a map of key and value pairs.

A new type creates with a type alias(type keyword) and Record type.

type emps = Record<string, string>

Data initialized using object syntax as seen below.

let emps: Record<string, string> = {
   {"name": "john" },
   {"id":  "1" }
};

Conclusion

Learned typescript dictionaries with multiple examples to declare a dictionary type in typescript

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.