Maps
What
A Map is a collection of key-value pairs where both keys and values can be of any type. In TypeScript, you specify these types using <K, V>.
How
Maps use set to add entries and get to retrieve them. They also provide a size property and are easily iterable:
const speeds = new Map<string, number>();
speeds.set("Anakin", 947);
speeds.set("Sebulba", 941);
for (const [racer, speed] of speeds) {
console.log(`${racer} raced at ${speed}`);
}
Why
Unlike standard objects, Map keys can be any type (including objects or symbols), and they maintain the insertion order of elements. They also provide built-in methods for checking existence (has) and deleting entries (delete) that are more ergonomic than object manipulation.
Summary
Use Map<K, V> when you need a robust dictionary with typed keys and values.