Welcome! Today, we'll delve into Maps, a data structure that organizes data as key-value pairs, much like a treasure box with unique labels for each compartment. Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging is required — that's the power of Maps! In this lesson, we'll understand Maps and learn how to implement them in TypeScript.
TypeScript implements Maps through the Map class. They hold data in key-value pairs with type safety. Let's create a Map, functioning as a catalog for a library:
In this Map, book1, book2, and book3 are keys, while the book titles serve as their respective values. The keys and values both specify types, ensuring type safety. Both keys and values are allowed to be of any type within typescript (primitives, objects, arrays and functions).
You can retrieve a book's title using its key straightforwardly with the get() method:
But what happens if you try to access a key that isn't present in the Map? This would return undefined.
As demonstrated, one method to verify the existence of a specific key in the Map is shown above. While this method is valid, it is usually not the most optimal approach. Alternatively, TypeScript provides the built-in has() function that returns a boolean value, offering a more standardized and concise way to check for the presence of a key:
