liveBook · Manning

Map

As explained in Essential TypeScript 5, Third Edition

Map is a JavaScript built-in collection that stores key/value pairs and permits keys and values of arbitrary types.

Map is a JavaScript collection for storing key/value pairs when ordinary objects are too restrictive. Keys and values may use arbitrary types, while TypeScript generic arguments can restrict the collection to a specific key and value type. section 2.2.6 section 4.4.2

Indexing to-do items by numeric ID

A typed collection can declare private itemMap = new Map<number, TodoItem>();. Each todo item's numeric id becomes its key: itemMap.set(item.id, item). A lookup uses itemMap.get(id), while [...itemMap.values()] produces an array that can be filtered before display. The generic declaration lets the compiler reject nonnumeric keys or values that are not TodoItem objects. section 2.2.6

Mapping product names to objects

A generic collection can use a product's name as its key: Map<string, T>. Adding an item calls this.items.set(newItem.name, newItem), and get(name) returns the matching object. The constrained type parameter ensures that T has the name property required by the map operations.

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains storage, lookup, iteration, and TypeScript generic restrictions through worked collections, without descending into runtime internals.
Examples
Uses TodoItem objects keyed by numeric IDs and products keyed by names.
What it assumes
Assumes JavaScript collection familiarity while teaching TypeScript generic key and value restrictions through concrete examples.
What you can do after
Apply it via JavaScript and TypeScript to build typed keyed collections, retrieve values, and iterate over stored objects.
How it connects
Connects Map with generic types, iterators, filtering, constrained type parameters, and Set.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.