The New Map() Feature in TypeScript: A Game-Changer for Your Code
Map is a built-in data structure for key-value pairs. Think of it as an Object, but with better ergonomics for dynamic keys.
20 Apr 2024

Map is a built-in data structure for key-value pairs. Think of it as an Object, but with better ergonomics for dynamic keys.
Why use Map over a plain Object?
Objects coerce all keys to strings. Map keeps keys as their original type — numbers, objects, even functions. It also maintains insertion order and has a .size property that actually works.
The basics
const myMap = new Map([
['key1', 'value1'],
['key2', 'value2'],
['key3', 'value3']
]);
myMap.set('key4', 'value4');
console.log(myMap.get('key1')); // "value1"
console.log(myMap.has('key1')); // true
myMap.delete('key1');
myMap.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Converting between Map and Object
const obj = Object.fromEntries(myMap);
console.log(obj); // { key2: "value2", key3: "value3", key4: "value4" }
const anotherObj = { a: 1, b: 2, c: 3 };
const fromObj = new Map(Object.entries(anotherObj));
console.log(fromObj); // Map(3) { 'a' => 1, 'b' => 2, 'c' => 3 }
The trade-off
Map is better for frequent additions and deletions, non-string keys, and when you need ordered iteration. But you can't serialize it directly to JSON. And most code still expects plain objects. If you're just storing config or passing data between functions, a plain object is simpler.
Use Map when it solves a real problem. Don't use it to be fancy.