Type modern syntax

INPUT · Slides

Type Map and Set

01 / 06

Map has types for keys and values

Map holds key–value pairs. Unlike an object, the key can be anything, not just a string.

In TypeScript you declare it as Map<key type, value type> in angle brackets.

const scores = new Map<string, number>();scores.set("Yui", 80);scores.set("Kei", 65);console.log(scores.get("Yui"));

Result

80

02 / 06

Set is a bag with no duplicates

Set holds values where the same value can only appear once. Great for removing duplicates from an array.

The type is Set<contents type>.

const tags = new Set<string>();tags.add("HTML");tags.add("CSS");tags.add("HTML");console.log(tags.size);

Result

2

03 / 06

Same idea as chapter 6

Map<string, number> and Set<string> work exactly like the Array<string> you read in chapter 6. Hand a type to a type to make a specific type.

Map takes two (key and value), Set takes one (contents). The count changes; the idea is the same.

const m: Map<string, number> = new Map();const s: Set<string> = new Set();console.log(m.size, s.size);

Result

0 0

04 / 06

Keys do not have to be strings

Object keys had to be strings, but a Map key can be anything you choose — a number, for instance.

Map<number, string> reads as "a number key paired with a string value".

const users = new Map<number, string>();users.set(1, "Yui");users.set(2, "Kei");console.log(users.get(1));

Result

Yui

05 / 06

The wrong type gets stopped

Declare Map<string, number> and then hand it a string for the value, and it is a type error. Catching that before you run anything is exactly what the type is for.

const scores = new Map<string, number>();scores.set("Yui", "eighty");

Result

Type error: Argument of type 'string' is not assignable to parameter of type 'number'.

06 / 06

forEach walks it in order too

Besides for...of, a Map also has forEach. The callback you pass gets called with "value, key" each time — a familiar feel if you know array forEach.

const scores = new Map<string, number>();scores.set("Yui", 80);scores.set("Kei", 65);scores.forEach((value, key) => {  console.log(`${key}: ${value}`);});

Result

Yui: 80
Kei: 65