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.
Production-Ready Systems with LLMs and Agents
A live Maven cohort, 5 October to 2 November: eight 90-minute sessions where you build LLM and agent systems that survive real traffic, real cost and real failure. Tuesdays and Thursdays, 7:30 to 9:00pm London.
Cohort 2 starts 5 October. Eight live sessions, $1,500.
View the live cohortKeep reading
- TypeScript Anti-Patterns That Cost You Twice: Build Time, Runtime, and the Interview
- The Frontend Toolchain Is Now Written in Rust and Go. What That Means for You
- oxlint vs ESLint: 12s to Under 1s, and What You Lose
- SystemJS Is Dead. Native ESM Finally Won.
- Replace Axios with a Simple Custom Fetch Wrapper (Production-Ready Guide)
- Stop Shipping ChatGPT Wrappers. Ship an Agent in TypeScript, or Don't Bother.