In a programming language, a dictionary generally refers to an object that maps keys to values. Dictionaries are very useful for accessing values using keys. In TypeScript and JavaScript, there isn’t a built-in “dictionary” data structure similar to other languages like Python’s dictionary. Instead, a dictionary is typically implemented using objects, Maps, interfaces, etc.
In this Answer, we’ll explore implementing a dictionary using an interface in TypeScript.
Here is an example of implementing a dictionary using the interface in TypeScript:
interface Dictionary<T>{[key: string]: T;}let stringDictionary: Dictionary<string> = {"key1": "value1"};console.log("stringDictionary:", stringDictionary);let numberDictionary: Dictionary<number> = {"key2": 5};console.log("numberDictionary:", numberDictionary);
In the code above:
Lines 1–3: We implement a dictionary using a generic interface Dictionary
. The <T>
denotes that this interface is generic and can be used with any type T
. Inside this interface, we define an index signature [key: string]: T;
. Any object of this interface can have any number of properties, where each property’s key
is a string
, and each property’s value
is of type T
.
Lines 5–8: We declare a variable stringDictionary
of type Dictionary<string>
to store string values. Inside this dictionary, we define a single key-value pair, where key1
is the key and value1
is the value. Lastly, we log the stringDictionary
object to the console.
Lines 10–13: Similarly, we define a variable numberDictionary
to store numeric values and log the object to the console.
In TypeScript, we can also use various methods to add new key pairs to the dictionary. Let’s explore some below:
Dot operator: This method is straightforward and readable when the key is a
Bracket notation: This method is useful when the key is not a valid identifier or when the key is stored in a variable. In this method, we write the key within brackets (as a string) and assign the value.
Using Object.assign()
: This method is useful for adding multiple key-value pairs simultaneously. It creates a new object by copying properties from one or more source objects to a target object. In this method, the existing dictionary and new key-value pairs are passed as arguments to the Object.assign()
method.
Using spread operator: This method is another way to add multiple key-value pairs to an object, creating a new object with the combined properties. In this method, we use the spread operator (...
) to spread the properties of the existing dictionary and the new key-value pairs into a new object.
Here are the examples of the methods mentioned above:
interface Dictionary<T>{[key: string]: T;}let stringDictionary: Dictionary<string> = {"key1": "value1",};console.log("stringDictionary:", stringDictionary);stringDictionary.key2 = "value2"; // Dot operatorstringDictionary["key3"] = "value3"; // Bracket notationObject.assign(stringDictionary, { key3: "value3" }); // Object.assign()stringDictionary = { ...stringDictionary, key4: "value4" }; // Spread operatorconsole.log("stringDictionary:", stringDictionary)
In the code above:
Lines 5–8: We declare a variable stringDictionary
with a key-value pair and log it to the console.
Line 10: We add a new key-value pair using a dot operator.
Line 11: We use the bracket notation to add a new key-value pair.
Line 12: To add a new key-value pair, we call Object.assign()
and pass the dictionary and key-value pair.
Line 13: We use the spread operator to add a new key-value pair in stringDictionary
.
Line 14: We log stringDictionary
to the console.
In TypeScript, we can access the key value in different ways. Let’s explore two popular methods below:
Dot operator: The most common way to access the key value is by using a dot between the object and the key. For example, dictionary.key1
.
Bracket notation: It is another popular way to use brackets around the key, just like accessing an array’s index. For example, dictionary["key1"]
. This method is very useful when the key is stored in a variable.
Here are the examples of both methods:
interface Dictionary<T>{[key: string]: T;}let stringDictionary: Dictionary<string> = {"key1": "value1","key2": "value2"};console.log("stringDictionary.key1:", stringDictionary.key1); // Dot operatorconsole.log("stringDictionary[\"key2\"]:", stringDictionary["key2"]); // Bracket notation
In the code above:
Lines 5–8: We declare a variable stringDictionary
and store two key-value pairs.
Line 10: We use the dot operator to access the value of the key key1
and log it to the console.
Line 11: We use the bracket notation to access the value of the key "key2"
and log it to the console.
We can iterate over a dictionary using multiple methods of Object
. Let’s discuss some of them below:
Object.keys()
: This method returns an array of the object’s keys.
Object.values()
: This method returns an array of the object’s values.
Object.entries()
: This method returns an array of key-value pairs.
Here the examples of iterating over a dictionary:
interface Dictionary<T>{[key: string]: T;}let stringDictionary: Dictionary<string> = {"key1": "value1","key2": "value2"};console.log("Keys using Object.keys() method:");console.log("Keys", Object.keys(stringDictionary));Object.keys(stringDictionary).forEach(key => {console.log("Value at", key, "is", stringDictionary[key]);});console.log("\nValues using Object.values() method");Object.values(stringDictionary).forEach(value => {console.log(value);});console.log("\nKey-value pairs using Object.entries() method");Object.entries(stringDictionary).forEach(([key, value]) => {console.log(key, value);});
In the code above:
Lines 10–14: We use the forEach()
method to get the list of keys. We iterate through the keys returned by the Object.keys()
method. Inside forEach()
method, we log the key and the associated value to the console.
Lines 16–19: We use the forEach()
method to iterate through the values returned by the Object.values()
method. Inside forEach()
method, we log the value to the console.
Lines 21–24: We use the forEach()
method to iterate through the key-value pairs returned by the Object.entries()
method. Inside forEach()
method, we log the key and value to the console.
To check if a key exists in a dictionary, we can use the in
operator or hasOwnProperty()
method. Here are the examples of both methods:
interface Dictionary<T>{[key: string]: T;}let stringDictionary: Dictionary<string> = {"key1": "value1","key2": "value2"};if ("key1" in stringDictionary) {console.log("Key1 exists in the dictionary.");}if (stringDictionary.hasOwnProperty("key2")) {console.log("Key2 exists in the dictionary.");}
In the code above:
Lines 10–12: Within the if
statement, we use the in
operator to check the existence of the key1
key. Inside the if
statement, we log the key existence to the console.
Lines 14–16: Similarly, within the if
statement, we use the hasOwnProperty
method to check the existence of the key2
key and log the key existence to the console.
We can remove a key-value pair from a dictionary using the delete
operator. Here is an example of deleting a key-value pair:
interface Dictionary<T>{[key: string]: T;}let stringDictionary: Dictionary<string> = {"key1": "value1","key2": "value2"};console.log("stringDictionary:", stringDictionary);delete stringDictionary.key1;console.log("stringDictionary after deleting key1:", stringDictionary);
Dictionaries are extremely versatile and can be used in a wide range of scenarios. Here are some practical examples:
Configuration settings: Dictionaries are ideal for storing configuration options. Using key-value pairs, we can easily retrieve and update configuration settings.
Lookup tables: Dictionaries can be used as lookup tables to quickly retrieve information based on a unique key. This is particularly useful for scenarios where we need to map keys to specific values.
Grouping data: Dictionaries can be used to aggregate data by specific keys, making it easy to organize and retrieve related data.
Dynamic object properties: Dictionaries are useful when we need to work with objects whose properties are not known at compile-time. They allow the dynamic addition and access of properties.
Counting occurrences: Dictionaries can be used to count the occurrences of items in a collection, such as counting the frequency of words in a text. We can assume the word is a key, and its occurrences can be incremented as a value.
Dictionaries in TypeScript are a powerful tool for managing collections of key-value pairs. They offer a flexible way to store and manipulate data, making them suitable for various use cases such as configuration settings, lookup tables, grouping data, handling dynamic object properties, and counting occurrences. By understanding and utilizing dictionaries effectively, we can write more efficient, readable, and maintainable TypeScript code.
Free Resources