Dictionaries and collections: Record, Map, and Set
Keep values under names that are data with Record, count with a Map whose get admits a missing key, and keep each value once with a Set. See why a Record’s brackets trust you while a Map’s get makes you write ?? 0, and choose the one a job needs.
Fundamentals
TypeScript
Dictionaries and collections: `Record`, `Map`, and `Set`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
On the fridge hangs a sheet of paper where you write down how long
your chores took. Monday, 30 minutes. Tuesday, 45. Then nothing
until Friday, 20. Nobody printed the days on the sheet in advance:
a day appears when you write it, and next to every day is the same
kind of thing, a number of minutes. Next to it hangs a shopping
list, where "milk" is written twice because two people noticed it
was gone. You will still buy one carton.
A Task is not like that sheet. Its outline lists its names, id
(short for identifier, the task's number), title and due, before
any task exists. In this lesson the names are data, values the program
meets as it runs: days, chores, whatever comes in. You learn three
ways to keep such a collection, one value that holds many others:
a Record, an object whose names are data; a Map, which adds
methods and tells you when a key is missing; and a Set, which keeps
each value once. By the end you can total a week of minutes, count how
often each chore was done, and cross out the repeats on a list.
Names that are data: Record
A collection where you look a value up by its name is called a
dictionary, after the book where you look up a word to find its
meaning. The name you look up is its key, the word lesson 6.9 used
for a property's name.
The fridge sheet is a dictionary: the days are its keys, the
minutes its values. In TypeScript its type is written
Record<string, number>. Record comes with TypeScript, and the
two types between the angle brackets fill it in: the first is the
type of every key, the second the type of every value. So
Record<string, number> reads "any text as a name, a number under
each". Types written in angle brackets after a name come back in
Module 10; for now, read them as you read string[], which says
what a list holds.
interface Task
Does: Names fixed by the outline, each with its own type
Never: It never takes a name the outline does not list
Record<string, number>
Does: Any name, as text; every value a number
Never: It never knows which names will be there
An interface lists its names; a Record takes any name
A Record is an ordinary object, so it is written in braces and
read with a dot or with square brackets, as lesson 6.9 read
rent["title"]. What changes is what TypeScript allows. A Task
refuses a property its outline does not list; a Record takes a
new day whenever you write one. Run this:
It prints the three days and Total: 95 minutes. Hover over
minutes in your editor: it says number. In lesson 6.9 the
values from Object.entries(rent) were any, and TypeScript
checked nothing done with them. Here the Record says what every
value holds, so total += minutes is checked, and
week["Tuesday"] = "45" is refused with Type 'string' is not assignable to type 'number'.
Even the loop lesson 6.9 refused works now. There rent[key], with a
key from Object.keys, was TS7053 (TS for TypeScript, then the
number of the message): a Task has no property for almost every
text. A Record<string, number> accepts every text as a name, so the
lookup is allowed:
It prints 75. But here a Record's square brackets trust you, as
a list's did in lesson 4.1: TypeScript says week["Sunday"] is a
number, because any text is a name, yet no Sunday was ever written
down.
Bad — counts a day nobody wrote down,
and the total quietly becomes NaN, short for not a number.
Good — a missing day counts as
0 minutes.
The first prints Planned: NaN minutes: week["Sunday"] is
undefined, and a number plus undefined gives NaN, as in
lesson 4.7's trace.
TypeScript lets both through, so the ?? 0 is yours to remember
whenever a name may not be there.
A Map: keys that come and go
Now count how many times you did each chore this week, from a list
like ["water", "milk", "water"]. The keys appear as the program
runs, a key's number goes up again and again, and you want to ask
which chores are there at all. That is the job a Map is made
for: a dictionary with its own methods.
You make one with new Map<string, number>(). The word new makes
a new, empty Map; Module 13 shows where new comes from. The angle
brackets are read as they were for Record: keys are text, values
are numbers. The box can be a const even though the Map will
change: as in lesson 6.7, const locks the box's arrow, not the
object it points at. With const tally = new Map<string, number>(),
these are its methods:
Write
What it does
tally.set("milk", 1)
Puts 1 under "milk", replacing what was there
tally.get("milk")
Gives back the value under "milk"
tally.has("milk")
Answers true or false
tally.delete("milk")
Takes the key and its value out
tally.size
How many keys it holds
The difference from a Record is in what get answers. Ask a Map for
a key it does not hold and it answers undefined, and its type says
so: tally.get("milk") is number | undefined, the same kind of "a
value, or nothing" lesson 3.3 taught, and as honest as lesson 4.1's
.at(). Press Next step to walk through a conversation with a
Map, or let it play:
Yourcode
tally
1
Your code to tally: set("milk",1)
2
Your code to tally: set("milk",2)
All 6 steps shown.Step 1 of 6: Your code → tally — set("milk", 1)Step 2 of 6: Your code → tally — set("milk", 2)Step 3 of 6: Your code → tally — get("milk")Step 4 of 6: tally → Your code — 2Step 5 of 6: Your code → tally — get("bread")Step 6 of 6: tally → Your code — undefined
All 6 steps shown.
The second set replaced the 1, because a key holds one value. That
undefined is in the Map's type too, where a Record's brackets
would have said number. So counting with a Map reads the old number,
uses 0 when there is none, adds one and sets it back. Press Step
to watch tally grow:
It prints Map(2) { 'water' => 2, 'milk' => 1 }, which is how Node
shows a Map: its size, then each key with an arrow to its value. Then
2 false 2, then water: 2 and milk: 1: a for...of over a Map
gives each pair, taken apart by place as in lesson 6.9, in the order
its key was first set, with no Object.entries needed.
Leave out the ?? 0 and TypeScript refuses the line with Object is possibly 'undefined'.. Lesson 3.3 showed this message as 'typedTask' is possibly 'undefined'.; tally.get(chore) is not a box with a
name, so the message says Object in its place, a plain word here,
not lesson 6.9's Object. TypeScript will not let you add 1 to a
value that may not be there.
A Set: each value once
Back to the shopping list with milk on it twice. A list keeps
everything you put in it, repeats included, because each item has
its own place. Sometimes the places do not matter and only one
question does: is it on the list? A Set keeps each value
once, and answers that question.
A list
Does: Keeps every item, in order, a repeat too
Never: It never notices that milk is there twice
A Set
Does: Keeps each value once, in the order it first came
Never: It never has places: nothing at [0]
Three items in: a list keeps all three, a Set keeps two
A Set is made with new, like a Map, and filled with add. has,
delete and size work as they do on a Map. Run this:
It prints Set(2) { 'milk', 'bread' } 2, then true false, then
milk and bread, each value once, in the order it came. The second
add("milk") changed nothing, without an error: a Set does not
complain about a repeat, it just keeps one.
The last three lines are the trick a Set is used for most. new Set(notes) makes a Set from a list, dropping the repeats; TypeScript
works out from the list that it is a Set<string>. Spread, from
lesson 6.8, then copies each value of the Set into new square
brackets, so
unique is a list again: [ 'milk', 'rent', 'bread' ], in the
order each item first came.
Which one to choose
All three hold many values. What sets them apart is what each one
checks for you.
You need
Use
Because
Values under names, one type
Record
A plain object, in braces
To notice a missing key
Map
get admits undefined
Each value once, "is it there?"
Set
add skips repeats
A Record and a Map can both count chores. Take a Map when keys
come and go and a missing one matters, and a Record for an object
you write out and read like any other.
Predict before you run
The program sets water twice. Decide what the last line prints
before you run it.
Predict
What does the last line print?
The common mistake: square brackets on a Map
A Record is read and written with square brackets, so after the
fridge sheet it feels natural to count chores the same way.
Common mistake
Reading and writing a Map with square brackets
You count the chores the way you would in a Record:
A Map keeps its keys inside, where only its methods reach.
Square brackets would read and write properties of the Map object
itself, which has none called water. TypeScript refuses both:
tally[chore] = … with Did you mean to call 'tally.set'?, and
tally[chore] on the right with the same message ending
'tally.get'. So nothing runs.
Element implicitly has an 'any' type because type 'Map<string, number>' has no index signature. Did you mean to call 'tally.set'?
The fix
Ask the Map with its methods:
It prints Map(2) { 'water' => 2, 'milk' => 1 }. Node without
TypeScript would have run the first version and printed Map(0) { water: 2, milk: 1 }: two stray properties stuck on the Map, and a Map
holding no keys at all. When the error is TS7052, with has no index signature in it (an index signature is what lets a type take any name
in square brackets, as a Record does) and a suggestion of get or
set, swap the brackets for the method. A Set has no places either:
shopping[0] is refused with TS7053; ask it with has, or loop
over it with for...of.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What does Record<string, number> describe?
Check yourself
How do you read the count under milk in the Map tally?
Check yourself
You only need to know if a chore was done today. Which?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Record, Map and Set
What things are
Word
What it means
Dictionary
Values looked up by a name, called a key
Record<string, number>
Any text as a name, a number under each
Map
A dictionary with methods; keys come and go as it runs
Set
Each value once, with no places
new
Makes a new Map or Set
Code
Write
What you get
week["Friday"] = 20
A new name in a Record
week["Sunday"] ?? 0
0 for a name nobody wrote
new Map<string, number>()
An empty Map: text keys, number values
tally.set("milk", 2)
2 under "milk", replacing what was there
tally.get("milk") ?? 0
The value, or 0 when the key is missing
tally.has("milk")
true or false
tally.delete("milk")
The key and its value taken out
for (… of tally)
Each pair, in the order keys were first set
new Set<string>()
An empty Set of text
shopping.add("milk")
Puts it in, unless it is there already
for (const item of shopping)
Each value of a Set, in the order it came
[...new Set(list)]
The list without its repeats
.size
How many keys or values a Map or Set holds
Rules
Module 6 on one page
Cheat sheet
Module 6: Objects and Collections
6.1 Objects and object types
Write
To
{ title: "Pay rent" }
Make an object; commas between parts
task.minutes
Read one property
{ title: string }
Write an object type; semicolons between
task: { title: string }
Give a box or a parameter that type
6.2 Optional and readonly properties
Write
To
task.done = true
Change one property
due?: string
Let a value leave due out
task.due ?? "not set"
Read an optional one, with a default
readonly id: number
Make a property read-only
6.3 Type aliases (type)
Write
To
type Task = { title: string };
Name an outline
const task: Task = …
Give a box that type
type Minutes = number;
Name any type, not only outlines
6.4 Interfaces and extends
Write
To
interface Task { title: string; }
Name an object's outline
interface PlannedTask extends Task { … }
Build an outline on Task
const task: Task = …
Where to go next
You can now keep values under names that are data: in a Record
when you write the names and every value has one type, in a Map
when keys come and go and a missing one must be noticed. You can
keep each value once in a Set, and turn a list with repeats into
one without. That closes Module 6: a task is an object, and you can
type it, copy it, take it apart and collect many of them.
Next is Union types, the first lesson of Module 7. You have used
one since lesson 3.3, string | undefined, and a Map's get gives
another, number | undefined. There a value may be one of several
kinds, such as string | number, and later in the module TaskKit's
tasks get a status that can only be one of a few words.
Before you move on, count today's chores in a Map with the set and
get ?? 0 line, put the same list in a Set, and print the Set's
size. Then add a chore you already did and run it again: its count
in the Map goes up, and the Set's size stays the same.
3
Your code to tally: get("milk")
4
tally to Your code: 2
5
Your code to tally: get("bread")
6
tally to Your code: undefined
Your code asks; the Map answers, undefined for a key it lacks
Rule
What it means
A Record's values
Typed: Object.entries gives them their type
A Record's brackets
Every name gives a number, even a missing one
get is honest
number | undefined: write ?? 0
One value per key
set again replaces it, in the same place
No brackets on a Map
TS7052: use get and set
No places in a Set
shopping[0]: TS7053; ask with has
Give a box that type, as with an alias
6.5 type or interface: a simple rule for choosing
Rule
What it means
One question
An object's outline: interface; else type
Their project
Follow the rule it already uses
One name, one outline
Never give two outlines the same name
6.6 Structural typing: shapes, not names; excess property checks
Rule
What it means
Shapes, not names
Any value with the properties fits
A missing property
Refused everywhere: TS2741
An extra property
Refused only in an object literal that meets a type
6.7 References vs copies: why changing one object changes another
Write
What happens
const other = rent
The arrow is copied; one object, two names
{ id: rent.id, … }
New braces: a new object
other === rent
true only for the same object
6.8 Destructuring and spread (and why spread is shallow)
Write
What happens
{ title, due } = rent
Two boxes, filled by property name
{ ...rent, due: day }
A copy with one property replaced
tags: [...rent.tags]
The inner list copied too
6.9 Iterating over objects: Object.keys and Object.entries
Write
What you get
Object.keys(rent)
The names: [ 'id', 'title', 'due' ]
Object.entries(rent)
The pairs: [ 'id', 1 ] first
rent[key]
TS7053: use Object.entries instead
6.10 Dictionaries and collections: Record, Map, and Set
Write
What you get
Record<string, number>
Any text as a name, a number under each
tally.get("milk") ?? 0
The value, or 0 when the key is missing
[...new Set(list)]
The list without its repeats
Exercise · Read the code
Count what is left in the Set
What does the last line print?
Exercise · Predict the result
Ask both for a missing day
Neither week nor tally holds Sunday. What does the last line
print?
Node prints
[ 'milk', 'bread', 'milk' ]
Node prints
Set(2) { 'milk', 'bread' }
rent
{ id: 1, title: "Pay rent", due: "Monday",}
week
{ Monday: 30, Tuesday: 45, Friday: 20,}
week.tsts
const week: Record<string, number> = { Monday: 30, Tuesday: 45 };week["Friday"] = 20;let total = 0;for (const [day, minutes] of Object.entries(week)) { console.log(`${day}: ${minutes} minutes`); total += minutes;}console.log(`Total: ${total} minutes`);
sum.tsts
const week: Record<string, number> = { Monday: 30, Tuesday: 45 };let sum = 0;for (const day of Object.keys(week)) { sum += week[day];}console.log(sum);
This program should add up the minutes planned for each day and
print Monday: 25 minutes, then Friday: 30 minutes. Every task
here has a day, so due is not optional. TypeScript refuses the
line inside the first loop. Fix that line, and leave the others as
they are.
Loading the editor…
Exercise · Write the code
Notice a chore done again
Write the loop. For each chore in done, print the chore the first
time it appears, and Again: and the chore every time after that.
Use the Set seen to remember what you have printed. The program
should print water, milk, Again: water, Again: milk.
Loading the editor…
ts
const tags = new Set<string>();tags.add("home");tags.add("money");tags.add("home");tags.delete("money");console.log(tags.size);