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 · 1 min read

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.
Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.
Forward Deployed AI Engineering: From Customer Problem to Production Value
A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.
January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.
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: Why I Replaced ESLint with oxlint
- 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.