Need to attach temporary metadata to an object without changing it? A Map stores explicit key-value pairs and lets keys be values of any type, including objects. Unlike ordinary object keys, Map keys are not converted to strings. section 10.2 section 10.2.1
A few mechanics make Map useful for more than dictionary-style lookups:
- Create a map, then use set, get, has, and delete to manage its entries; size reports the number of mappings. section 10.2.1
- Object keys match by identity: changing an object does not change its key, but a separate lookalike object is not the same key. Two variables referencing the same object do match. section 10.2.1
- Iterate with for...of in insertion order, or use keys() and values() for just one side of the mappings. Object.fromEntries can convert a map to an object, but its keys become strings. section 10.2.2
Listing 10.11 Creating a map
interface Ninja {
name: string;
}
interface NinjaMetadata {
homeIsland: string;
}
const ninja1 = { name: "Yoshi" };
const ninja2 = { name: "Hattori" };
const ninja3 = { name: "Kuma" };
const ninjaMetadataMap = new Map<Ninja, NinjaMetadata>(); #A
ninjaMetadataMap.set(ninja1, { homeIsland: "Honshu" }); #B
ninjaMetadataMap.set(ninja2, { homeIsland: "Hokkaido" }); #B
console.assert( #C
ninjaMetadataMap.get(ninja1)?.homeIsland === "Honshu" && #C
ninjaMetadataMap.get(ninja2)?.homeIsland === "Hokkaido", #C
"The first two ninjas have metadata", #C
); #C
console.assert( #D
ninjaMetadataMap.get(ninja3) === undefined, #D
"There is no mapping for the third ninja", #D
); #D
console.assert( #E
ninjaMetadataMap.size === 2, #E
"We've created two mappings", #E
); #E
ninjaMetadataMap.delete(ninja1); #F
console.assert( #G
!ninjaMetadataMap.has(ninja1) && #G
ninjaMetadataMap.size === 1, #G
"There's no first ninja mapping anymore!", #G
); #G
ninjaMetadataMap.clear(); #H
console.assert(
ninjaMetadataMap.size === 0,
"All mappings have been cleared",
);
See a typed Map associating ninja objects with separate metadata, including lookup and size checks. section 10.2.1
Listing 10.12 Iterating over a map
const directory = new Map<string, string>(); #A
directory.set("Yoshi", "+81 26 6462 9152"); #B
directory.set("Kuma", "+81 52 2378 6462"); #B
directory.set("Hiro", "+81 76 2771 4624"); #B
for (const [key, value] of directory) { #C
console.assert(key !== null, "Key:" + key); #C
console.assert(value !== null, "Value:" + value); #C
} #C
for (const key of directory.keys()) { #D
console.assert(key !== null, "Key:" + key); #D
console.assert( #D
directory.get(key) != null, #D
"Value:" + directory.get(key), #D
); #D
} #D
for (const value of directory.values()) { #E
console.assert(value !== null, "Value:" + value); #E
} #E
Compare iteration over entries with iteration over keys or values in a phone directory. section 10.2.2
















































