In this Blog we will learn about how to Build a type_safe Dictionary using TypeScript.

Dictionary in TypeScript:

A dictionary is a type of data structure that is commonly used in programming languages. It is critical for JavaScript developers to work with type-safe dictionaries because storing different types of data within the same dictionary will result in conflicts or unexpected issues.

 
Type_safe Dictionaries in TypeScript:

Type-safety can be added to our dictionaries with the introduction of Typescript. Because of this, we have total control over the dictionary entries we make and the keys you  utilise. It also gives you the ability to assert certain things about the values that the dictionaries have returned.

Building a type _safe Dictionary in TypeScript:

In TypeScript, There Are 3 Methods To Avoid Type Issues. they are:

  1. indexed object notation method.
  2. Record<Keys, Type> utility method.
  3.  Using Map method.

indexed object notation method:

The indexed object notation can be used to determine the type of data. Let’s create a dictionary with string types for the key and value.

Syntax:

const dictionary: { [key: string]: string } = {};

dictionary.studentname = ‘Abcd’;

dictionary.status = true;//boolean type is not assignable to the  string
 
Using the Record<Keys, Type> utility method:
 The TypeScript tool RecordKeys, Type> is used to create key-value objects. If you wish to create a key type as unions or enums, this is a fantastic option.
Example for Record:
const dictionary: Record<string, string> = {};
dictionary.firstName = ‘X’;
dictionary.lastName = ‘y’;
dictionary.fullname = ‘Abcd’;
 
Example for Union type:
 type UserFields = ‘studentName’ | ‘fatherName’;
let dictionaryUnion: Record<UserFields, string> = {
    studentName : ‘surya’,
    fatherName : ‘dany’
}; // Works very well
 
dictionaryUnion = {
    studentName: ‘Student’,
    fatherName: ‘Father’,
    address: ‘canada’ // Type is not assignable to type ‘Record<UserFields, string>’
}; 

Using “map” method in TypeScript:

JavaScript type-safe dictionaries can be made by using Map. Let’s create a straightforward dictionary in TypeScript where the key is a string and the value is a number.

Example:

const dictionary = new Map<string, number>();

dictionary.set(‘JavaScript’, 9); // No Error

dictionary.set(‘HTML’, 9); // Works

// Argument of type ‘string’ is not assignable to parameter of type ‘number’

 

dictionary.set(‘react’, ‘9’); // Error

For any Help or Queries Contact us on info@crmonce.com or +918096556344