Skip to content

Map and Set ​

Map and Set follow JavaScript's semantics: insertion-ordered iteration, SameValueZero keys (NaN equals NaN, -0 equals 0), and iterators that see entries added or deleted during iteration the way Node's do.

ts
// Map and Set with insertion-ordered iteration, plus the array methods that pair with them.
const text = "the quick brown fox jumps over the lazy dog the end";

const counts = new Map<string, number>();
for (const word of text.split(" ")) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts.get("the"), counts.has("cat"), counts.size);

const byCount = [...counts.keys()].sort(
  (a: string, b: string): number => (counts.get(b) ?? 0) - (counts.get(a) ?? 0),
);
console.log(byCount.slice(0, 3));

const lengths = new Set<number>();
for (const word of counts.keys()) lengths.add(word.length);
console.log(lengths, lengths.has(5));
lengths.delete(3);
console.log([...lengths].join(","));
console.log(counts);
text
3 false 9
[ 'the', 'quick', 'brown' ]
Set(3) { 3, 5, 4 } true
5,4
Map(9) {
  'the' => 3,
  'quick' => 1,
  'brown' => 1,
  'fox' => 1,
  'jumps' => 1,
  'over' => 1,
  'lazy' => 1,
  'dog' => 1,
  'end' => 1
}

A Map can start from a list of [key, value] pairs written inline, and keeps their order:

ts
// A Map built from a literal list of [key, value] pairs keeps their order.
const ports = new Map<string, number>([
  ["http", 80],
  ["https", 443],
  ["ssh", 22],
]);
ports.set("http", 8080);
for (const name of ports.keys()) console.log(name, ports.get(name));
console.log(ports);
text
http 8080
https 443
ssh 22
Map(3) { 'http' => 8080, 'https' => 443, 'ssh' => 22 }

The supported methods are listed, straight from the compiler, in the subset reference.

Limits today ​

  • Iterating a Map directly (for (const [k, v] of m)) and m.entries() are rejected (CS1222); iterate m.keys() and read m.get(k).
  • new Map(...) accepts only an array literal of pairs, not a variable holding them (CS1000); create an empty Map and set each entry in a loop. new Set(xs) takes any array.
  • Tuples with different element types ([string, number]) are rejected (CS1233); use an object with named fields.
  • A union as the key type is rejected (CS1233).
  • Plain objects are not dictionaries: index signatures ({ [k: string]: T }) are rejected (CS1207). Use a Map.

Next: async / await.