A Complete Guide to Understand TypeScript Dictionary

TypeScript Dictionary

A dictionary in TypeScript is a common data structure that lets you store data in key-value pairs.

Unlike arrays that use numbers for indexing, dictionaries use keys which can be strings or other types, based on how you set it up.

A TypeScript Dictionary often referred to as a map or associative array, is a key data structure in computer science.

It’s a collection of key-value pairs that don’t maintain any specific order. In TypeScript, you can construct a dictionary using an indexed interface, the Record utility type, or the ES6 Map object.

With TypeScript’s type-checking features, you can transform these dynamic JavaScript dictionaries into type-safe dictionaries that accept only a specific key-value type declaration, such as string for keys and number for values.

A type-safe dictionary will trigger compile-time and linter errors if a developer tries to store data types that are not defined in the accepted dictionary key-value types.

Here’s the basic syntax for declaring a dictionary:

interface Dictionary {
  [key: string]: string;
}

You can declare a dictionary using an interface or type alias in TypeScript.

After you declare, you can initialize a dictionary as you can see in the following code:

let sampleDictionary: Dictionary = {};

How to Create a Dictionary in TypeScript?

There are multiple ways to create a dictionary in TypeScript:

  1. Using an Indexed Interface

The simplest way to create a dictionary is to define an indexed interface and apply it to an empty object.

Here’s how you can do it:

interface IGrades {
}

const grades: IGrades = {};

grades['Programming'] = '95';
grades['Networking'] = '90';
grades['ComEng'] = '99';

console.log(grades);

The example code shows that the grades dictionary has been successfully created and populated with the subjects and their corresponding grades.

The keys in the dictionary are the subjects (Programming, Networking, ComEng), and the values are the grades 95, 90, 99).

Output:

{ Programming: '95', Networking: '90', ComEng: '99' }

Apart from that, you can also define a generic indexed interface for reusability with different value types.

Here’s an example:

interface IGrades<T> {
  [key: string]: T;
}

const grades: IGrades<string> = {};
grades['Programming'] = '95';
console.log(grades);

const grades2: IGrades<number> = {};
grades2['Networking'] = 90;
console.log(grades2);

Output:

{ Programming: '95' }
{ Networking: 90 }

  1. Using the Record Utility Type

You can also construct a dictionary in TypeScript using the Record utility type.

Here’s an example:

const grades: Record<string, string> = {};

grades['Programming'] = '95';
grades['Networking'] = '90';
grades['ComEng'] = '99';

console.log(grades);

Output:

{ Programming: '95', Networking: '90', ComEng: '99' }

  1. Using the ES6 Built-in Map Object

Lastly, you can use the ES6 Map object to create a dictionary.

Here’s an example:

const grades = new Map();

grades.set('Programming', '95');
grades.set('Networking', '90');
grades.set('ComEng', '99');

console.log(grades);

Output:

Map (3) {"Programming" => "95", "Networking" => "90", "ComEng" => "99"} 

The main advantage of using the Map object over other methods is its API methods for managing key/value pairs.

How to Add and Retrieve Values in TypeScript Dictionary?

You can add values to a TypeScript dictionary by using the assignment operator (=).

Here’s an example using an object as a dictionary:

interface ISampleDictionary {
  [key: string]: string;
}

const dictionary: ISampleDictionary = {};

// Adding values
sampledictionary['key1'] = 'value1';
sampledictionary['key2'] = 'value2';=

To retrieve values from a TS dictionary by using the key associated with the value.

Here’s an illustration of how you can do it:

// Retrieving values
console.log(sampledictionary['key1']); // Outputs: 'value1'
console.log(sampledictionary['key2']); // Outputs: 'value2'

Now, let’s check a complete example code:

// Create a Map
const grades = new Map<string, string>();

// Add values
grades.set('Programming', '95');
grades.set('Networking', '90');
grades.set('ComEng', '99');

// Retrieve values
console.log(grades.get('Programming')); 
console.log(grades.get('Networking')); 
console.log(grades.get('ComEng')); // 

Output:

'95'
'90'
'99'

How to Update and Delete Values in TypeScript Dictionary?

You can update values in a TS dictionary by assigning a new value to an existing key.

Here’s an example using an object as a dictionary:

interface IGrades {
}

const grades: IGrades = {};
grades['Programming'] = '95';

// Updating value
grades['Programming'] = '99';
console.log(grades['Programming']); 

Output:

99

To delete values from a TS dictionary by using the delete keyword.

Here’s how you can do it:

// Deleting value
delete grades['Programming'];
console.log(dictionary['Programming']); // Outputs: undefined

As you can see, we’re trying to delete the value associated with ‘Programming’ from the dictionary object.

You can also use the Map object to create a dictionary and use the delete method to remove values:

// Create a Map
const grades = new Map();

// Add values
grades.set('Programming', '95');
grades.set('Networking', '90');

// Delete value
grades.delete('Programming');
console.log(grades.get('Programming'));

Output:

 undefined

Conclusion

Knowing how to use TypeScript dictionaries is really important if you want to be good at TypeScript coding. This guide has taught you all the important stuff about dictionaries.

You can use dictionaries for lots of things like settings, user info, or complicated structures. TypeScript dictionaries are a great tool for coders.

I hope this article has given you some insights and helped you understand the TypeScript Dictionaries.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment