Skip to content
HopperHopper

Course navigation

Phase 2 · Data and functionsDay 7

Objects, type aliases, maps and sets

  • About 65 minutes
  • 10 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 65 minutes

By the end you will be able to

  1. Build an object literal, read and change its properties, and predict what the checker says about a property that does not exist.
  2. Describe the shape of data with a type alias, including optional and readonly properties, and use it for nested objects and arrays of objects.
  3. Loop over an object with Object.keys, Object.values, and Object.entries, and count things with a Record or a Map.
  4. Choose between a plain object, a Record, a Map, and a Set for a task, and pull values out of an object with destructuring.

What to remember from earlier

Section 1 of 10

7.1 Object Literals and Dot Access

Before you start, set up a new project folder named day07 exactly as you set up day01 in 1.2: open the folder in VS Code, run npm init -y and npm install --save-dev typescript in its terminal, and type the same tsconfig.json. Every program today goes in that folder.

Day 6 gave you the array: one value that holds many values of the same kind, in order, reached by position. That fits a list of scores or a list of names. But think about one book. It has a title (a string), a page count (a number), and whether it is in stock (a boolean): three values of different kinds that belong together, and none of them has a natural “position.” You could keep them in three separate variables, bookTitle, bookPages, bookInStock, but nothing in the program says they describe the same book, and a second book would need three more.

An object is one value that holds several named values. Each named value is a property: a key, which is the name, paired with a value. Where an array answers “what is at position 2?”, an object answers “what is the pages?” You write one as an object literal: curly braces around a list of key: value pairs separated by commas.

const name = {
  key1: value1,
  key2: value2,
};
Piece What it is
{ and } Mark the object. These are the same braces as a block, but after = they make a value, not a block of code
key: value One property: the name, a colon, then any expression for the value
, Separates properties. A comma after the last one is allowed, and VS Code’s formatter adds it

To read a property, write the object’s name, a dot, and the key: book.pages. This is dot notation. The result is an ordinary value with the key’s type, so book.pages - 10 is arithmetic and book.title.length is a string’s length.

Worked example: One book, three facts

book.ts
const book = {
  title: "Dune",
  pages: 412,
  inStock: true,
};
console.log(book.title);
console.log(book.pages);
console.log(`${book.title} has ${book.pages} pages`);
book.pages = 416;
console.log(book.pages);
console.log(book);
console.log(typeof book);
Dune
412
Dune has 412 pages
416
{ title: 'Dune', pages: 416, inStock: true }
object
Line What happens
1–5 Builds an object with three properties and stores it in book
6–7 book.title is the string "Dune"; book.pages is the number 412
8 Properties work inside a template literal like any other value
9 Assigns a new value to the pages property; the other two properties are untouched
11 Node shows the whole object on one line, keys without quotes and string values in single quotes
12 typeof an object is "object", the same word Day 2 showed for null

Line 9 may surprise you: book is a const, and yet the program changed something inside it. A const promises only that the name book will always refer to this same object; it says nothing about the object’s contents. You met the same rule on Day 6, where push could add to a const array. What const forbids is book = somethingElse.

Now vary it. A property’s value can be any expression, including a variable or a method call, and a key can be a quoted string when it is not a valid variable name:

cat.ts
const name: string = "Mochi";
const birthYear = 2021;
const thisYear = 2026;
const cat = {
  name: name,
  age: thisYear - birthYear,
  sound: "meow".toUpperCase(),
  "favorite toy": "feather",
};
console.log(cat);
console.log(cat["favorite toy"]);
console.log(cat["age"]);
const dog = { name, age: 3 };
console.log(dog.name);
{ name: 'Mochi', age: 5, sound: 'MEOW', 'favorite toy': 'feather' }
feather
5
Mochi

Lines 5 to 7 work out each value when the object is built: age becomes 5 and sound becomes "MEOW", and the object stores the results, not the expressions. Line 8’s key has a space in it, so it must be written in quotes, and Node prints it in quotes too. A key like that cannot follow a dot (cat.favorite toy would be read as two things), so line 11 uses bracket notation: the key as a string inside square brackets. Line 12 shows the brackets work for ordinary keys as well; cat["age"] and cat.age are the same property. Use the dot unless the key forces you not to.

Line 13 is a shortcut you will see often. When a variable has the same name as the key, { name, age: 3 } means { name: name, age: 3 }: this is shorthand property syntax.

Key idea

An object literal { key: value, ... } groups named values into one value. book.pages reads a property and book.pages = 416 changes it, even when book is a const, because const only fixes which object the name refers to. Bracket notation book["pages"] does the same with the key as a string.

Watch out

Two names, one object. Assigning an object to a second variable does not make a second object. Just as with arrays on Day 6, both names now refer to the same object, and a change made through one name shows through the other:

shared-book.ts
const book = { title: "Dune", pages: 412 };
const copy = book;
copy.pages = 500;
console.log(book.pages);
console.log(copy === book);
const realCopy = { ...book };
realCopy.pages = 100;
console.log(book.pages);
console.log(realCopy === book);
500
true
500
false

Line 3 changes pages through copy, and line 4 shows that book.pages changed too: there is only one object. Line 5’s === asks “are these the same object?”, not “do they have the same contents?”, and the answer is true. To get a separate object, spread the original into a new literal, as line 6 does: the three dots from Day 6’s [...items] work on objects too, copying every property into a fresh object. Now line 7’s change does not reach book, and line 9 shows the two are different objects. Keep this picture in mind whenever you see = with an object on the right: it copies the reference to the object, not the object.

Pause and try

Question 1 · Tracing

Predict exactly what this program shows.

predict-object.ts
const player = { name: "Rio", score: 40, lives: 3 };
player.score += 15;
player.lives--;
const rival = player;
rival.score = 0;
console.log(player.name.toUpperCase());
console.log(player.score, player.lives);
console.log(`${player["name"]} has ${player.lives} lives`);
Check your reasoning
RIO
0 2
Rio has 2 lives
Line What happens player after
2 score becomes 40 + 15 { name: 'Rio', score: 55, lives: 3 }
3 lives goes down by one { name: 'Rio', score: 55, lives: 2 }
4–5 rival is the same object, so setting rival.score changes it { name: 'Rio', score: 0, lives: 2 }
6 player.name is a string, so toUpperCase() works on it RIO
8 player["name"] is the same property as player.name Rio has 2 lives

Line 7 shows 0 2, not 55 3, because line 5 changed the one object both names refer to.

Reread 7.1 Object Literals and Dot Access if any line differed.

Question 2 · Multiple choice

const pet = { name: "Mochi", age: 5 }; Which line does the checker reject?

  1. pet.age = 6;
  2. pet.age += 1;
  3. pet = { name: "Mochi", age: 6 };
  4. console.log(pet["name"]);
Check your reasoning

C. const means the name pet can never be made to refer to a different object, and line C tries exactly that (TS2588, the same message as assigning to any constant).

  • A is wrong: changing a property is allowed. const protects the name, not the contents.
  • B is wrong for the same reason: += changes the property, not what pet refers to.
  • D is wrong: bracket notation with the key as a string reads a property just as pet.name does.

Reread 7.1 Object Literals and Dot Access if you chose differently.

Section 2 of 10

7.2 Object Types: What the Checker Sees

On Day 2 you saw that the checker gives every variable a type, worked out from its first value when you write no annotation. What type does it give book? Hover over book in book.ts and VS Code shows:

const book: { title: string; pages: number; inStock: boolean; }

That is an object type: a list of the property names, each with its type, between braces, separated by semicolons. It describes the object’s shape: which keys exist and what kind of value each holds. Notice pages: number, not pages: 412. For a const holding a plain number, Day 2 showed the exact value as the type, but a property can be assigned again, like a let, so the checker gives it the wider type number.

The shape is fixed at the moment the object is created, and the checker uses it to catch three kinds of mistake. Here are the first two:

unknown-property.ts
const book = { title: "Dune", pages: 412 };
console.log(book.tilte);
console.log(book.author);
book.author = "Frank Herbert";
unknown-property.ts:2:18 - error TS2551: Property 'tilte' does not exist on type '{ title: string; pages: number; }'. Did you mean 'title'?
unknown-property.ts:3:18 - error TS2339: Property 'author' does not exist on type '{ title: string; pages: number; }'.
unknown-property.ts:4:6 - error TS2339: Property 'author' does not exist on type '{ title: string; pages: number; }'.

Line 2 has a typo, and the checker says so, even suggesting the right spelling (TS2551 is TS2339 with a suggestion). Line 3 asks for a property the object never had; run with node, it would quietly show undefined, as reading past the end of a string did on Day 3, but the checker stops it first. Line 4 is the one that surprises people: you cannot add a property after the object is made, because author is not part of the shape. If the book needs an author, put it in the literal from the start. Fix or delete this file before your next check.

The third kind is a value of the wrong type:

wrong-type-property.ts
const book = { title: "Dune", pages: 412 };
book.pages = "many";
book.title = 7;
wrong-type-property.ts:2:1 - error TS2322: Type 'string' is not assignable to type 'number'.
wrong-type-property.ts:3:1 - error TS2322: Type 'number' is not assignable to type 'string'.

This is Day 1’s TS2322, now for a property: pages was created holding a number, so it holds numbers for the rest of the program, exactly as a variable keeps its type. Fix or delete this file too.

Worked example: Using properties in calculations

Since every property has a known type, the checker lets you use it wherever that type is allowed, and works out the type of the result:

reading-progress.ts
const book = { title: "Dune", pages: 412 };
let pagesRead = 150;
console.log(`${book.pages - pagesRead} pages left`);
pagesRead += 100;
const fraction = pagesRead / book.pages;
console.log(`${(fraction * 100).toFixed(0)}% of ${book.title} read`);
const done = pagesRead >= book.pages;
console.log(done);
262 pages left
61% of Dune read
false
Line Expression Type the checker gives Value
3 book.pages - pagesRead number 262
5 pagesRead / book.pages number 0.6067…
6 (fraction * 100).toFixed(0) string "61"
7 pagesRead >= book.pages boolean false

Hover over fraction and done to see the types in the third column. Nothing here is new except where the numbers come from: a property behaves exactly like a variable of its type.

Key idea

The checker works out an object’s type, its shape, from the literal: which keys it has and the type of each value. After that, reading or adding a key that is not in the shape is TS2339, and assigning the wrong kind of value to a property is TS2322.

Pause and try

Question 3 · Tracing

Which lines does npx tsc reject? Write each message. Then say what lines 2 and 3 would show if the rejected lines were deleted.

predict-shape.ts
const city = { name: "Lima", population: 10000000 };
console.log(city.name.length);
console.log(city.population * 2);
console.log(city.country);
city.population = "ten million";
city.name = city.name + ", Peru";
console.log(city);
Check your reasoning
predict-shape.ts:4:18 - error TS2339: Property 'country' does not exist on type '{ name: string; population: number; }'.
predict-shape.ts:5:1 - error TS2322: Type 'string' is not assignable to type 'number'.
  • Line 4 reads a property that is not in the shape: the object was created with only name and population.
  • Line 5 assigns a string to a property created with a number.
  • Line 6 is accepted: city.name + ", Peru" is a string, and name holds strings.

Without lines 4 and 5, line 2 shows 4 (the length of "Lima") and line 3 shows 20000000. If you typed this program, fix or delete it before your next check.

Reread 7.2 Object Types: What the Checker Sees if you picked different lines.

Section 3 of 10

7.3 Type Aliases

A reading list has many books, and every one of them should have the same shape. If each is a separate literal, nothing checks that: one book could have pages while another has pageCount by mistake, and the checker would happily give each its own shape. And when you want to say “this variable will hold a book” before you have the book, an annotation like let current: { title: string; pages: number } is long, and you would have to repeat it for every variable.

The fix is to give the shape a name. A type alias is a declaration that names a type, so you can use the name wherever the type is needed:

type Name = {
  key1: type1;
  key2: type2;
};
Piece What it is
type The keyword that starts a type alias. It exists only for the checker; node strips it out
Name The new type’s name, written in PascalCase (a capital first letter), like Book or Student
key1: type1; One property, as the hover showed it: the name, a colon, and a type, ending with a semicolon

Declaring type Book = { ... } creates no object. It only tells the checker what a Book looks like, the way the word “boolean” names a kind of value without being one. You then use Book as an annotation, exactly where Day 2 put number or string:

Worked example: Two books of one type

book-alias.ts
type Book = {
  title: string;
  pages: number;
};
const dune: Book = { title: "Dune", pages: 412 };
const hobbit: Book = { title: "The Hobbit", pages: 310 };
console.log(dune.pages + hobbit.pages);
let current: Book = dune;
console.log(current.title);
current = hobbit;
console.log(current.title);
722
Dune
The Hobbit

Lines 1 to 4 declare the alias. Lines 5 and 6 each annotate a constant with : Book, so the checker compares each literal with the shape: both have a string title and a number pages, so both are accepted. Line 7 adds the two pages properties. Line 8 declares a let that may hold any Book, and line 10 switches it from one book to the other; both are allowed because both are Books. Hover over dune and VS Code now shows const dune: Book, the name you chose, instead of the braces.

With the alias in place, the checker can catch a literal that does not match it. A missing property:

missing-property.ts
type Book = {
  title: string;
  pages: number;
};
const sketch: Book = { title: "Untitled" };
console.log(sketch.pages);
missing-property.ts:5:7 - error TS2741: Property 'pages' is missing in type '{ title: string; }' but required in type 'Book'.

The message names the shape the literal has, { title: string; }, and the shape it was supposed to have, Book. Every property in the alias is required unless you say otherwise (7.4 shows how). And an extra property:

extra-property.ts
type Book = {
  title: string;
  pages: number;
};
const dune: Book = { title: "Dune", pages: 412, author: "Frank Herbert" };
console.log(dune.title);
extra-property.ts:5:49 - error TS2353: Object literal may only specify known properties, and 'author' does not exist in type 'Book'.

Column 49 is where author begins. Why reject an extra property, when the book really does have an author? Because in an object literal written straight into an annotated place, an unknown key is almost always a typo for a known one, such as Name for name, and the checker would rather tell you now than let a misspelled property go unread forever. If Books should have authors, add author: string; to the alias, and every Book must then have one. Fix or delete both files before your next check.

Key idea

type Book = { title: string; pages: number }; names a shape so it can be written once and used in many annotations. A literal assigned to a Book must have every property in the alias (TS2741 when one is missing) and no others (TS2353 when there is an extra one), each with the right type.

Pause and try

Question 4 · Debugging

Two students do not match their type. Predict both messages, explain them, and write the fix.

student-wrong.ts
type Student = {
  name: string;
  grade: number;
  present: boolean;
};
const ana: Student = { name: "Ana", grade: "9", present: true };
const ben: Student = { Name: "Ben", grade: 10, present: false };
console.log(ana.name, ben.name);
Check your reasoning
student-wrong.ts:6:37 - error TS2322: Type 'string' is not assignable to type 'number'.
student-wrong.ts:7:24 - error TS2561: Object literal may only specify known properties, but 'Name' does not exist in type 'Student'. Did you mean to write 'name'?

On line 6, column 37 is "9": grade must be a number, and "9" in quotes is a string. On line 7, Name with a capital N is a different key from name, so the literal has an unknown property (TS2561 is TS2353 with a spelling suggestion), and because name is then missing too, fixing the capital letter fixes both problems at once.

student-fixed.ts
type Student = {
  name: string;
  grade: number;
  present: boolean;
};
const ana: Student = { name: "Ana", grade: 9, present: true };
const ben: Student = { name: "Ben", grade: 10, present: false };
console.log(ana.name, ben.name);
Ana Ben

If you typed the original program, fix or delete it before you go on.

Reread 7.3 Type Aliases if you missed either message.

Section 4 of 10

7.4 Optional and Readonly Properties

Not every book has a subtitle. With the alias from 7.3, you would have to give every Book a subtitle, perhaps an empty string, and then remember that "" means “none.” Real data is often like this: a middle name, an apartment number, a note on an order. The alias needs a way to say “this property may be left out.”

Put a question mark after the key: subtitle?: string;. That makes an optional property. A literal may include it or leave it out, and the checker accepts both. But what do you get when you read a property that was left out? The same thing Day 3 gave for a character past the end of a string: undefined.

Worked example: A book with a subtitle and one without

optional-subtitle.ts
type Book = {
  title: string;
  pages: number;
  subtitle?: string;
};
const guide: Book = {
  title: "Birds of Peru",
  subtitle: "A Field Guide",
  pages: 240,
};
const novel: Book = { title: "Dune", pages: 412 };
console.log(guide.subtitle);
console.log(novel.subtitle);
if (novel.subtitle) {
  console.log(`Subtitle: ${novel.subtitle}`);
} else {
  console.log("No subtitle");
}
console.log(guide);
console.log(novel);
A Field Guide
undefined
No subtitle
{ title: 'Birds of Peru', subtitle: 'A Field Guide', pages: 240 }
{ title: 'Dune', pages: 412 }

Line 4 makes subtitle optional. guide includes it (and the properties can come in any order; subtitle is written before pages here), while novel leaves it out, and the checker accepts both literals. Line 12 shows the subtitle; line 13 shows undefined, with no error from anyone, because an optional property that was left out simply has no value. Line 14 checks before using it: from Day 4, undefined is falsy, so the else block runs for novel. Lines 19 and 20 show that novel really has only two properties; the subtitle is not stored as undefined, it is absent.

Hover over novel.subtitle and VS Code shows string | undefined. You met this type with at() on Day 3: read it as “a string or undefined,” a type with two possibilities that Day 9 teaches fully. The checker uses it to stop you using the property as if it were certainly there:

subtitle-length.ts
type Book = {
  title: string;
  pages: number;
  subtitle?: string;
};
const novel: Book = { title: "Dune", pages: 412 };
console.log(novel.subtitle.length);
subtitle-length.ts:7:13 - error TS18048: 'novel.subtitle' is possibly 'undefined'.

undefined has no length, so if the subtitle was left out, line 7 would crash with a TypeError when run. The checker reports it before that can happen. The fix is what optional-subtitle.ts did: put the use inside if (novel.subtitle) { ... }. Inside that block the checker knows the property is a string, because the condition ruled out undefined, the same following-your-conditions idea that Day 4 previewed. Fix or delete subtitle-length.ts now.

The opposite need also comes up: a property that must never change once the object exists, like a book’s ISBN or a ticket’s id. Put readonly before the key, and the checker rejects any assignment to it:

readonly-isbn.ts
type Book = {
  readonly isbn: string;
  title: string;
  pages: number;
};
const dune: Book = { isbn: "978-0441013593", title: "Dune", pages: 412 };
dune.pages = 416;
dune.isbn = "000-0000000000";
readonly-isbn.ts:8:6 - error TS2540: Cannot assign to 'isbn' because it is a read-only property.

Line 7 is accepted, because pages is an ordinary property; line 8 is not. This is the property version of Day 6’s readonly string[], and like it, it exists only in the checker: node would run line 8 without complaint. Fix or delete this file, then compare the version that respects the rule:

readonly-ok.ts
type Book = {
  readonly isbn: string;
  title: string;
  pages: number;
};
const dune: Book = { isbn: "978-0441013593", title: "Dune", pages: 412 };
dune.pages = 416;
console.log(dune.isbn, dune.pages);
const reprint: Book = { isbn: "978-0441172719", title: dune.title, pages: 528 };
console.log(reprint.isbn, reprint.pages);
978-0441013593 416
978-0441172719 528

A readonly property can still be given a value when the object is built, as on lines 6 and 9; what it cannot do is change afterwards. A reprint with a new ISBN is a new object.

Key idea

subtitle?: string is an optional property: a literal may leave it out, and reading it then gives undefined, so check it with if before using it as a string (TS18048 otherwise). readonly isbn: string can be set only in the literal; assigning to it later is TS2540.

Pause and try

Question 5 · Tracing

Predict exactly what this program shows, and say whether npx tsc accepts it.

predict-optional.ts
type Ticket = {
  readonly id: number;
  event: string;
  seat?: string;
};
const a: Ticket = { id: 1, event: "Concert", seat: "B12" };
const b: Ticket = { id: 2, event: "Film" };
console.log(a.seat, b.seat);
console.log(b.seat ? "Reserved" : "Any seat");
console.log(a.seat ? a.seat.toLowerCase() : "none");
b.event = "Late film";
console.log(b);
Check your reasoning

npx tsc accepts it, and it shows:

B12 undefined
Any seat
b12
{ id: 2, event: 'Late film' }
  • Line 8: a.seat is "B12"; b has no seat, so b.seat is undefined.
  • Line 9: undefined is falsy, so the conditional operator gives "Any seat".
  • Line 10: "B12" is truthy, and inside the true branch the checker knows a.seat is a string, so toLowerCase() is allowed: b12.
  • Line 11 is accepted: only id is readonly; event may change.
  • Line 12: b still has just two properties; seat was never added.

Reread 7.4 Optional and Readonly Properties if any line differed.

Question 6 · Multiple choice

With type Ticket = { readonly id: number; seat?: string }; and const t: Ticket = { id: 1 };, which line does the checker accept?

  1. t.id = 2;
  2. console.log(t.seat.length);
  3. t.seat = "C4";
  4. const u: Ticket = { seat: "C4" };
Check your reasoning

C. seat is optional, which means it may be missing, but it is an ordinary property otherwise: assigning a string to it is allowed, and afterwards t.seat is "C4".

  • A is wrong: id is readonly, so assigning to it is TS2540.
  • B is wrong: t.seat is string | undefined, so using .length without a check is TS18048.
  • D is wrong: id is not optional, so a literal without it is TS2741.

Reread 7.4 Optional and Readonly Properties if you chose differently.

Section 5 of 10

7.5 Nested Objects and Arrays of Objects

A property’s value can be any value, and that includes another object or an array. A book’s author has a name and a birth year of their own, which belong together just as the book’s facts do. Putting one object inside another makes a nested object, and a type alias can describe it by using another alias as a property’s type.

Worked example: A book with an author inside

nested-book.ts
type Author = {
  name: string;
  born: number;
};
type Book = {
  title: string;
  pages: number;
  author: Author;
};
const dune: Book = {
  title: "Dune",
  pages: 412,
  author: { name: "Frank Herbert", born: 1920 },
};
console.log(dune.author.name);
console.log(dune.author.born + 45);
const writer = dune.author;
console.log(writer.name.length);
console.log(dune);
Frank Herbert
1965
13
{
  title: 'Dune',
  pages: 412,
  author: { name: 'Frank Herbert', born: 1920 }
}

Line 8 says the author property holds an Author, the alias declared on lines 1 to 4; an alias must be declared before it is used in another one. Line 13 is an object literal inside an object literal. To reach the author’s name, line 15 chains two dots: dune.author is the inner object, and .name reads its property. Line 17 stores the inner object in its own variable, which is a reference to the same inner object, not a copy. Line 19 shows that Node prints a nested object across several lines once it gets too long for one.

The other direction is just as useful: an array whose elements are objects. The type is written like any array type from Day 6, with the alias in front of the brackets: Book[], “an array of Books.” Every loop and accumulator pattern from Day 5 works on it; the only change is that each element has properties.

reading-list.ts
type Book = {
  title: string;
  pages: number;
};
const books: Book[] = [
  { title: "Dune", pages: 412 },
  { title: "The Hobbit", pages: 310 },
  { title: "Emma", pages: 474 },
];
console.log(books.length);
console.log(books[1].title);
let totalPages = 0;
let longest = books[0];
for (const book of books) {
  totalPages += book.pages;
  if (book.pages > longest.pages) {
    longest = book;
  }
}
console.log(`${totalPages} pages in ${books.length} books`);
console.log(`Longest: ${longest.title}`);
books.push({ title: "Matilda", pages: 240 });
console.log(books[books.length - 1]);
3
The Hobbit
1196 pages in 3 books
Longest: Emma
{ title: 'Matilda', pages: 240 }
Line What happens
5–9 An array literal of three object literals; the checker checks each against Book
11 books[1] is the second object, and .title reads its property
13 longest starts as the first book; its type is Book
14–19 for...of gives each Book in turn; the sum and the “find the maximum” pattern of Day 5
22 push takes an object literal, checked against Book like any other
23 The last element, reached with length - 1 as on Day 6

Line 16 compares book.pages with longest.pages, and line 17 makes longest refer to the current book object. By the end, longest is the Emma object itself, not a copy, so longest.title on line 21 reads from it.

Key idea

A property can hold another object (author: Author), reached by chaining dots: dune.author.name. An array of objects has the type Book[], and for...of gives one object at a time, so every Day 5 loop pattern works on it.

Watch out

Reading an element that is not there. On Day 6 you saw that indexing past the end of an array gives undefined, while the checker believes an element is always there. With objects, the next dot turns that into a crash:

past-the-end.ts
type Book = {
  title: string;
  pages: number;
};
const books: Book[] = [
  { title: "Dune", pages: 412 },
  { title: "The Hobbit", pages: 310 },
];
console.log(books[1].title);
console.log(books[2].title);

npx tsc reports nothing: it treats books[2] as a Book. But node past-the-end.ts shows The Hobbit and then stops with:

TypeError: Cannot read properties of undefined (reading 'title')

books[2] is undefined because the array has only two elements, and undefined has no properties. The message tells you which property was being read, title, which is your clue that the thing in front of it was undefined. Check books.length before indexing by a number, or use for...of, which never runs off the end.

Pause and try

Question 7 · Tracing

Predict exactly what this program shows.

predict-nested.ts
type Team = {
  name: string;
  captain: { name: string; number: number };
  wins: number[];
};
const teams: Team[] = [
  { name: "Owls", captain: { name: "Ana", number: 7 }, wins: [3, 1] },
  { name: "Foxes", captain: { name: "Ben", number: 10 }, wins: [2, 2, 2] },
];
let best = teams[0];
for (const team of teams) {
  if (team.wins.length > best.wins.length) {
    best = team;
  }
}
console.log(`${best.name}, captain ${best.captain.name}`);
console.log(teams[0].wins[1] + teams[1].captain.number);
teams[0].captain.name = "Cleo";
console.log(teams[0].captain);
Check your reasoning
Foxes, captain Ben
11
{ name: 'Cleo', number: 7 }
  • Lines 10 to 15: best starts as the Owls, with 2 wins. The Foxes have 3, so 3 > 2 makes best the Foxes object. Line 16 chains into it: best.captain.name is "Ben".
  • Line 17: teams[0].wins[1] is the second win of the first team, 1; teams[1].captain.number is 10; the sum is 11.
  • Line 18 changes the first captain’s name through two dots, and line 19 prints that inner object: the name is now Cleo, the number still 7.

Reread 7.5 Nested Objects and Arrays of Objects if any line differed.

Section 6 of 10

7.6 Object.keys, Object.values, and Object.entries

A report card holds a score for each subject: { math: 90, art: 85, music: 72 }. To average them, you want to loop over the scores. But for...of is for arrays and strings, and an object is neither:

loop-over-object.ts
const scores = { math: 90, art: 85, music: 72 };
for (const score of scores) {
  console.log(score);
}
loop-over-object.ts:2:21 - error TS2488: Type '{ math: number; art: number; music: number; }' must have a '[Symbol.iterator]()' method that returns an iterator.

The message is wordy, but it means “you cannot for...of over this.” (Run with node, it crashes with scores is not iterable.) An object has no order of positions to walk through; it has keys. Fix or delete this file.

What you can do is ask for the object’s keys, or its values, or both, as an array, and loop over that. Three built-in functions do it, each written with Object. in front and the object as the argument:

Call Gives For scores
Object.keys(scores) The keys, as an array of strings [ 'math', 'art', 'music' ]
Object.values(scores) The values, as an array [ 90, 85, 72 ]
Object.entries(scores) Each key with its value, as an array of pairs [ [ 'math', 90 ], [ 'art', 85 ], [ 'music', 72 ] ]

Each pair from Object.entries is a Day 6 tuple, [string, number]: the key first, then the value. The keys come back in the order the properties were written.

Worked example: Averaging and listing a report card

scores-keys.ts
const scores = { math: 90, art: 85, music: 72 };
console.log(Object.keys(scores));
console.log(Object.values(scores));
console.log(Object.entries(scores));
let total = 0;
for (const score of Object.values(scores)) {
  total += score;
}
console.log(`Average: ${(total / Object.keys(scores).length).toFixed(1)}`);
for (const [subject, score] of Object.entries(scores)) {
  console.log(`${subject.padStart(6)}: ${score}`);
}
[ 'math', 'art', 'music' ]
[ 90, 85, 72 ]
[ [ 'math', 90 ], [ 'art', 85 ], [ 'music', 72 ] ]
Average: 82.3
  math: 90
   art: 85
 music: 72

Lines 2 to 4 show the three arrays. Line 6 loops over the values array with the Day 5 summing pattern; hover over score and VS Code shows number, because every value in scores is a number, so Object.values gives a number[]. Line 9 divides by the number of keys. Line 10 is the most useful form: for...of over the entries, with Day 6’s array destructuring in the loop header, so each pair is split into subject and score as it arrives. Day 3’s padStart lines up the subject names.

Which one to use? keys when you only need the names, values when you only need the numbers, and entries when you need both at once, which is most of the time.

Key idea

An object cannot be looped with for...of directly. Object.keys(obj), Object.values(obj), and Object.entries(obj) give its keys, its values, or [key, value] pairs as an array, and for (const [key, value] of Object.entries(obj)) visits every property.

Pause and try

Question 8 · Tracing

Predict exactly what this program shows.

predict-entries.ts
const stock = { apples: 12, pears: 0, kiwis: 5 };
console.log(Object.keys(stock).length);
let soldOut = "";
for (const [fruit, count] of Object.entries(stock)) {
  if (count === 0) {
    soldOut = fruit;
  }
}
console.log(soldOut);
console.log(Object.values(stock).includes(5));
console.log(Object.keys(stock)[2].toUpperCase());
Check your reasoning
3
pears
true
KIWIS
  • Line 2: Object.keys(stock) is an array of three strings, so its length is 3.
  • Lines 4 to 8: the pairs arrive as ["apples", 12], ["pears", 0], ["kiwis", 5]. Only the second has count === 0, so soldOut becomes pears.
  • Line 10: Object.values(stock) is [12, 0, 5], and Day 6’s includes finds 5: true.
  • Line 11: the third key is "kiwis"; toUpperCase() gives KIWIS.

Reread 7.6 Object.keys, Object.values, and Object.entries if any line differed.

Section 7 of 10

7.7 Record for Dictionary-Shaped Data

So far every object has had a fixed set of keys, known when you wrote the program: a book always has a title and pages. Now think about a shop’s stock, counted by product name. New products arrive while the program runs, so the keys are not known in advance, and the thing you want to look up is “the count for whatever name is in this variable.” Try that on a fixed-shape object:

variable-key.ts
const book = { title: "Dune", pages: 412 };
const field: string = "pages";
console.log(book[field]);
variable-key.ts:3:13 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ title: string; pages: number; }'.
  No index signature with a parameter of type 'string' was found on type '{ title: string; pages: number; }'.

field is annotated string, so it could hold any string, and the checker cannot promise that book[field] names a real property. (In 7.1, cat["age"] was accepted because "age" written in the brackets is a known key.) The second line of the message names what is missing: an index signature, a rule in the type that says “any key of this type is allowed.” Fix or delete this file.

The built-in type Record<KeyType, ValueType> is exactly such a rule. Record<string, number> means “an object whose keys are any strings and whose values are all numbers”: a dictionary, where you look up a value by a word, like looking up a definition.

Worked example: Stock counts by product name

stock.ts
const stock: Record<string, number> = { apple: 12, pear: 0 };
stock["kiwi"] = 5;
stock.mango = 8;
stock.apple -= 2;
console.log(stock);
const wanted: string = "kiwi";
console.log(stock[wanted]);
console.log(stock["banana"]);
console.log(stock["banana"] === undefined);
delete stock.pear;
console.log(Object.keys(stock));
{ apple: 10, pear: 0, kiwi: 5, mango: 8 }
5
undefined
true
[ 'apple', 'kiwi', 'mango' ]
Line What happens
1 The annotation says any string key is allowed; the literal starts with two
2–3 Adds new keys. Both notations work, and adding is allowed because the type permits any string key
4 Changes an existing value, 12 - 2
7 Looks up a key held in a variable, which 7.2’s fixed shape could not do
8–9 A key that was never added gives undefined, and === undefined tests for that
10 The delete operator removes a property, key and value together

Line 8 is the catch. The checker gives stock["banana"] the type number, because the Record promised that every string key leads to a number, but at run time a key that was never added has no value. This is the same gap as indexing past the end of an array: the checker trusts you, and node gives undefined. So before using a value from a Record, check it as line 9 does, or make sure the key was added.

The most common thing to do with a dictionary is to count. Letter by letter, the program below asks “have I seen this key yet?”, starts it at 0 if not, and then adds one:

letter-counts.ts
const word: string = "banana";
const counts: Record<string, number> = {};
for (const letter of word) {
  if (counts[letter] === undefined) {
    counts[letter] = 0;
  }
  counts[letter] += 1;
}
console.log(counts);
for (const [letter, count] of Object.entries(counts)) {
  console.log(`${letter}: ${"*".repeat(count)}`);
}
{ b: 1, a: 3, n: 2 }
b: *
a: ***
n: **

Line 2 starts with an empty object; the annotation is what makes it a dictionary rather than an object with no properties at all. Lines 4 to 6 handle a letter’s first appearance, and line 7 counts it, the same accumulator pattern from Day 5, but with one accumulator per key. Lines 10 to 12 then walk the result with Object.entries from 7.6. A shorter way to write lines 4 to 7 is counts[letter] = (counts[letter] || 0) + 1;: from Day 4, || gives the left side when it is truthy and otherwise the right, so undefined || 0 is 0 on the first visit and the stored count after that. (You will see this form again in 7.8.)

A plain object with a type alias and a Record are both objects, and Object.entries works on both. The difference is what the checker knows:

Question type Book = { title: string; pages: number } Record<string, number>
Which keys exist? Exactly title and pages Any string; add them freely
Can a key be in a variable? No (TS7053) Yes
Does reading a key give a value? Always undefined if never added
Can the values have different types? Yes, one type per key No, all the same type

Key idea

Record<string, number> is a dictionary: an object whose keys can be any string, added while the program runs, and whose values are all numbers. Reading a key that was never added gives undefined, although the checker says number, so check with === undefined or || 0 first.

Pause and try

Question 9 · Tracing

Predict exactly what this program shows.

predict-record.ts
const prices: Record<string, number> = { tea: 2, cake: 4 };
const order: string[] = ["tea", "cake", "tea", "soup"];
let total = 0;
let unknown = 0;
for (const item of order) {
  if (prices[item] === undefined) {
    unknown++;
  } else {
    total += prices[item];
  }
}
console.log(total, unknown);
prices.soup = 3;
console.log(Object.keys(prices).length);
console.log(prices["cake"] > prices.tea);
Check your reasoning
8 1
3
true
item prices[item] Branch total unknown
"tea" 2 else 2 0
"cake" 4 else 6 0
"tea" 2 else 8 0
"soup" undefined if 8 1

Line 13 adds soup as a third key, so line 14 shows 3. Line 15 compares 4 with 2, mixing both notations: true.

Reread 7.7 Record for Dictionary-Shaped Data if any line differed.

Question 10 · Multiple choice

A program keeps the number of times each visitor’s name has been seen. Names are read from a list while the program runs. Which type fits the counts?

  1. { name: string; seen: number }
  2. Record<string, number>
  3. number[]
  4. string[]
Check your reasoning

B. The keys are names that are not known when the program is written, and every value is a count, so a dictionary from string to number is the fit.

  • A is wrong: that shape holds one name and one count. A fixed shape cannot gain a key per visitor.
  • C is wrong: an array of numbers has positions, not names; you could not look up a count by name.
  • D is wrong: an array of names records who was seen, but not how many times.

Reread 7.7 Record for Dictionary-Shaped Data if you chose differently.

Section 8 of 10

7.8 Map

A Record is a plain object pressed into service as a dictionary, and it shows: its keys must be strings, reading a missing key gives a quiet undefined that the checker does not warn about, and finding how many entries it has takes Object.keys(stock).length. JavaScript has a value built for the job: a Map, a collection of key–value pairs with methods for every operation, where the keys can be of any type.

const name = new Map<KeyType, ValueType>();

new Map<string, number>() makes an empty map whose keys will be strings and whose values numbers; the types in angle brackets tell the checker what to allow, since an empty map has no entries to learn from. Then:

Method What it does Gives
set(key, value) Stores the value under the key, replacing any old one The map itself
get(key) Looks up a key The value, or undefined
has(key) Asks whether the key is present true or false
delete(key) Removes the key and its value true if it was there
size How many entries there are (a property, not a method) A number

Worked example: Counting words with a Map

word-map.ts
const counts = new Map<string, number>();
counts.set("apple", 3);
counts.set("pear", 1);
counts.set("apple", 4);
console.log(counts.get("apple"));
console.log(counts.get("plum"));
console.log(counts.has("pear"), counts.has("plum"));
console.log(counts.size);
counts.delete("pear");
console.log(counts);
for (const [word, count] of counts) {
  console.log(`${word} appears ${count} times`);
}
4
undefined
true false
2
Map(1) { 'apple' => 4 }
apple appears 4 times

Line 4 sets apple again, so its old value 3 is replaced; line 5 shows 4. Line 6 asks for a key that was never set and gets undefined, but, unlike a Record, the checker knows this can happen: hover over counts.get("plum") and it shows number | undefined, the “or undefined” type from 7.4. Line 8’s size is 2, and after line 9 deletes pear, Node prints the map on line 10 with its size and each entry as key => value. Line 11 loops straight over the map, no Object.entries needed: each turn gives a [key, value] pair, destructured in the header as in 7.6. A map remembers the order the keys were first added.

Because get may give undefined, the checker will not let you do arithmetic on its result directly, and it will not let you use brackets on a map at all:

map-bracket.ts
const counts = new Map<string, number>();
counts.set("apple", 3);
console.log(counts["apple"]);
console.log(counts.get("apple") + 1);
map-bracket.ts:3:13 - error TS7052: Element implicitly has an 'any' type because type 'Map<string, number>' has no index signature. Did you mean to call 'counts.get'?
map-bracket.ts:4:13 - error TS2532: Object is possibly 'undefined'.

Line 3 is the habit from Record: a map’s entries are not properties, so brackets find nothing, and the checker even suggests get. Line 4 is the real protection: counts.get("apple") might be undefined, and undefined + 1 is NaN, so the checker refuses. Fix or delete this file. For counting, the || 0 form from 7.7 is the answer: counts.set(word, (counts.get(word) || 0) + 1), which the checker accepts because undefined || 0 is a number. (Day 9 teaches ??, a cleaner operator for exactly this.)

Now vary the key type, and build a map from pairs:

seat-map.ts
const seats = new Map<number, string>();
seats.set(12, "Ana");
seats.set(14, "Ben");
seats.set(3, "Cleo");
console.log(seats.get(14));
console.log(seats);
const pairs = new Map([
  ["hot", 2],
  ["cold", 1],
]);
pairs.set("cold", (pairs.get("cold") || 0) + 1);
pairs.set("iced", (pairs.get("iced") || 0) + 1);
console.log(pairs);
Ben
Map(3) { 12 => 'Ana', 14 => 'Ben', 3 => 'Cleo' }
Map(3) { 'hot' => 2, 'cold' => 2, 'iced' => 1 }

Lines 1 to 4 use numbers as keys, seat numbers, which a Record cannot do (object keys are always strings; stock[3] would quietly become stock["3"]). Line 6 shows the keys unquoted, and in the order added, not sorted. Line 7 builds a map from an array of [key, value] tuples; the checker reads the types from them, so this is Map<string, number> without the angle brackets. Lines 11 and 12 are the counting form: cold already exists, so it goes from 1 to 2, while iced is new, so undefined || 0 starts it at 0 and it becomes 1.

So which should you use? All three are objects, but they fit different jobs:

Use When
A plain object with a type alias A fixed set of keys you know when you write the program, like a Book
Record<string, T> String keys added at run time, when you want object syntax and Object.entries
Map<K, V> Keys added and removed at run time, keys that are not strings, size, or a safer get

Key idea

new Map<string, number>() holds key–value pairs with set, get, has, delete, and size; get gives number | undefined, so the checker makes you handle a missing key. Loop over a map with for (const [key, value] of map). Keys can be any type, and the order of insertion is kept.

Pause and try

Question 11 · Tracing

Predict exactly what this program shows.

predict-map.ts
const ages = new Map<string, number>();
ages.set("Ana", 15);
ages.set("Ben", 16);
ages.set("Ana", 17);
ages.delete("Cleo");
console.log(ages.size);
console.log(ages.get("Ana"), ages.get("Cleo"));
console.log(ages.has("Ben") && ages.get("Ben") === 16);
let oldest = "";
let oldestAge = 0;
for (const [name, age] of ages) {
  if (age > oldestAge) {
    oldest = name;
    oldestAge = age;
  }
}
console.log(oldest);
Check your reasoning
2
17 undefined
true
Ana
  • Line 4 replaces Ana’s 15 with 17, so the map still has two entries, and line 5’s delete of a key that is not there changes nothing: size is 2.
  • Line 7: get("Ana") is 17; get("Cleo") is undefined.
  • Line 8: has("Ben") is true, and get("Ben") === 16 is true, so && gives true.
  • Lines 11 to 16: the pairs arrive as ["Ana", 17] then ["Ben", 16]. 17 beats 0, so oldest becomes "Ana"; 16 does not beat 17. The result is Ana.

Reread 7.8 Map if any line differed.

Section 9 of 10

7.9 Set

Sometimes you do not need a value for each key; you only need to know which keys there are. Who has visited the site today, whatever the count? Which tags appear on the menu, each once? An array can hold them, but it allows duplicates, so every time you add a name you first have to search with includes. A Set is a collection of values with no duplicates: adding a value that is already there changes nothing.

const name = new Set<ValueType>();
Method What it does Gives
add(value) Puts the value in, unless it is already there The set itself
has(value) Asks whether the value is in the set true or false
delete(value) Removes the value true if it was there
size How many values there are (a property) A number

Worked example: Who visited today?

visitors.ts
const visitors = new Set<string>();
visitors.add("Ana");
visitors.add("Ben");
visitors.add("Ana");
visitors.add("Cleo");
console.log(visitors.size);
console.log(visitors.has("Ben"), visitors.has("Dan"));
visitors.delete("Ben");
console.log(visitors);
for (const name of visitors) {
  console.log(name);
}
3
true false
Set(2) { 'Ana', 'Cleo' }
Ana
Cleo

Four add calls, but line 4 adds "Ana" a second time, and a set ignores it: line 6’s size is 3. Line 7 asks about two names. Line 9 prints the set after "Ben" is removed; Node shows a set much like an array, with its size in front. Line 10 loops over the values in the order they were first added. Note there is no get: a set has nothing to look up, because the value is the key. The question a set answers is only “is this in?”

The second thing a set is for is removing duplicates from an array, which Day 6’s first practice exercise made you do by hand. new Set(array) builds a set from the array’s values, dropping repeats, and Day 6’s spread turns it back into an array:

unique-tags.ts
const tags: string[] = ["hot", "milk", "cold", "hot", "milk", "hot"];
const unique = new Set(tags);
console.log(unique.size);
console.log([...unique]);
console.log([...unique].join(", "));
console.log(tags.length - unique.size);
3
[ 'hot', 'milk', 'cold' ]
hot, milk, cold
3

Line 2 gets its type from the array, so this is a Set<string>. Line 4’s [...unique] is a new array holding each tag once, in first-seen order, and line 5 joins it into one string with Day 3’s join. Line 6 counts the duplicates: six tags, three different ones.

Key idea

new Set<string>() holds each value at most once, with add, has, delete, and size. new Set(array) removes duplicates, and [...set] turns it back into an array. Use a set when the question is “is this in?” and a map when each key needs a value.

Watch out

A set has no positions. It is not an array, so names[0] means nothing to it:

set-index.ts
const names = new Set(["Ana", "Ben"]);
console.log(names[0]);
set-index.ts:2:13 - error TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Set<string>'.
  Property '0' does not exist on type 'Set<string>'.

If you need “the first one,” spread it into an array first: [...names][0]. Fix or delete this file.

Objects in a set are compared by reference. Remember from 7.1 that === on two objects asks whether they are the same object. A set uses that same test:

set-objects.ts
const points = new Set<{ x: number; y: number }>();
const origin = { x: 0, y: 0 };
points.add(origin);
points.add(origin);
points.add({ x: 0, y: 0 });
console.log(points.size);
console.log(points.has(origin));
console.log(points.has({ x: 0, y: 0 }));
2
true
false

Lines 3 and 4 add the same object twice, which counts once. Line 5 adds a new object literal that happens to have the same contents, and that counts as a second value, because it is a different object: size is 2. Line 8 asks about yet another new literal, and the answer is false. Sets and map keys are reliable for numbers and strings, which compare by value; for objects they track identity, not contents.

Pause and try

Question 12 · Tracing

Predict exactly what this program shows.

predict-set.ts
const seen = new Set<number>();
const rolls: number[] = [4, 2, 4, 6, 2, 4];
let repeats = 0;
for (const roll of rolls) {
  if (seen.has(roll)) {
    repeats++;
  }
  seen.add(roll);
}
console.log(seen.size, repeats);
console.log([...seen]);
console.log(seen.has(1) || rolls.includes(6));
Check your reasoning
3 3
[ 4, 2, 6 ]
true
roll seen.has(roll) repeats seen after
4 false 0 { 4 }
2 false 0 { 4, 2 }
4 true 1 { 4, 2 }
6 false 1 { 4, 2, 6 }
2 true 2 { 4, 2, 6 }
4 true 3 { 4, 2, 6 }

Three different values were rolled and three rolls were repeats. Line 11 spreads the set into an array in first-seen order. Line 12: seen.has(1) is false, so || goes on to rolls.includes(6), which is true.

Reread 7.9 Set if any line differed.

Question 13 · Multiple choice

Which task is a Set the best fit for?

  1. Storing a book’s title, pages, and author
  2. Counting how many times each word appears in a text
  3. Keeping the list of email addresses that have already been sent a reminder, so none gets two
  4. Keeping scores in the order they were entered, including repeats
Check your reasoning

C. The only question asked is “has this address been seen?”, and each address should be there at most once: has and add on a Set<string> do exactly that.

  • A is wrong: a fixed set of named properties of different types is a plain object with a type alias.
  • B is wrong: each word needs a value, its count, which is a Map or a Record.
  • D is wrong: repeats must be kept and order by position matters, so that is an array.

Reread 7.9 Set and the comparison table in 7.8 Map if you chose differently.

Section 10 of 10

7.10 Object Destructuring

In a loop over Book[], nearly every line starts with book.: book.title, book.pages. Copying each property into its own variable makes the code shorter to read, but writing const title = book.title; for every property is tedious. On Day 6 you pulled a tuple apart by position with const [name, score] = pair;. Objects have no positions, but they have keys, and the same idea works by name.

Object destructuring declares several variables from one object’s properties in a single statement. Put the keys you want inside braces on the left of =:

const { key1, key2 } = object;

This declares key1 and key2 as new constants holding object.key1 and object.key2. The braces on the left do not build an object; they take one apart.

Worked example: The long way and the short way

destructure-book.ts
type Book = {
  title: string;
  pages: number;
  subtitle?: string;
};
const guide: Book = { title: "Birds of Peru", pages: 240 };
const title = guide.title;
const pages = guide.pages;
console.log(`${title}: ${pages} pages`);
const { pages: length, subtitle = "(none)" } = guide;
console.log(length, subtitle);
const books: Book[] = [
  { title: "Dune", pages: 412 },
  { title: "Emma", pages: 474 },
];
for (const { title, pages } of books) {
  console.log(`${title} has ${pages} pages`);
}
Birds of Peru: 240 pages
240 (none)
Dune has 412 pages
Emma has 474 pages

Lines 7 and 8 are the long way. Line 10 shows two extras in one statement. pages: length takes the pages property but calls the new variable length, which is a rename: the key on the left of the colon, your chosen name on the right. subtitle = "(none)" gives a default, used only when the property is missing or undefined; since guide has no subtitle, subtitle becomes "(none)", and its type is plain string, because the default rules out undefined. Line 16 is where destructuring shines: the loop header pulls title and pages straight out of each Book, and the body uses the bare names.

Put the two kinds side by side, and note that in object destructuring the order does not matter, only the names:

destructure-both.ts
type Book = {
  title: string;
  pages: number;
};
const guide: Book = { title: "Birds of Peru", pages: 240 };
const { title, pages } = guide;
console.log(title, pages);
const pair: [string, number] = ["Birds of Peru", 240];
const [name, size] = pair;
console.log(name, size);
const { pages: count, title: heading } = guide;
console.log(count, heading);
Birds of Peru 240
Birds of Peru 240
240 Birds of Peru
Line Pattern Matched by
6 { title, pages } from an object Key name: title gets guide.title
9 [name, size] from a tuple Position: name gets pair[0]
11 { pages: count, title: heading } Key name, then renamed; order is free

Key idea

const { title, pages } = book; declares variables from an object’s properties by name. { pages: length } renames, { subtitle = "(none)" } gives a default for a missing property, and the pattern works in a for...of header: for (const { title } of books).

Watch out

A colon in a pattern renames; it does not annotate. After a day of writing title: string inside type aliases, this looks like it says title is a string:

destructure-rename-trap.ts
type Book = {
  title: string;
  pages: number;
};
const guide: Book = { title: "Birds of Peru", pages: 240 };
const { title: string } = guide;
console.log(string);
console.log(typeof string);
Birds of Peru
string

The checker accepts it, and the program runs. What it did was take guide.title and store it in a new variable named string, which line 7 prints. string is not a reserved word, so nobody complains. To annotate a destructuring, put the whole shape after the closing brace, const { title }: Book = guide;, though you rarely need to, since the checker already knows the property’s type. Rename this variable before you go on.

Destructuring a key that is not there is TS2339, the same as guide.author would be:

destructure-missing.ts
type Book = {
  title: string;
  pages: number;
};
const guide: Book = { title: "Birds of Peru", pages: 240 };
const { author, pages } = guide;
console.log(author, pages);
destructure-missing.ts:6:9 - error TS2339: Property 'author' does not exist on type 'Book'.

Fix or delete this file before your next check.

Pause and try

Question 14 · Tracing

Predict exactly what this program shows.

predict-destructure.ts
type Player = {
  name: string;
  score: number;
  team?: string;
};
const players: Player[] = [
  { name: "Rio", score: 40, team: "Owls" },
  { name: "Sam", score: 55 },
];
for (const { name, score, team = "solo" } of players) {
  console.log(`${name} (${team}): ${score}`);
}
const { score: best, name } = players[1];
console.log(best, name.length);
Check your reasoning
Rio (Owls): 40
Sam (solo): 55
55 3
  • Line 10 destructures each Player in the loop header. Rio has a team, so the default is not used. Sam has none, so team becomes "solo".
  • Line 13 takes players[1], Sam, and renames score to best; name keeps its own name. Line 14 shows 55 and the length of "Sam", 3.

Reread 7.10 Object Destructuring if any line differed.

Wrap-up · 1 of 8

Putting it together

A café menu is an array of items, each with a name, a price, some tags, and sometimes a note. From it, the program wants the list of all tags, how many items carry each tag, a quick price lookup by name for adding up an order, and a printed menu. Before you type it, make sure npx tsc is clean in your day07 folder: fix or delete any broken file from today.

menu.ts
type Item = {
  name: string;
  price: number;
  tags: string[];
  note?: string;
};
const menu: Item[] = [
  { name: "Latte", price: 3.5, tags: ["hot", "milk"] },
  { name: "Iced tea", price: 2.75, tags: ["cold"], note: "seasonal" },
  { name: "Cocoa", price: 3, tags: ["hot", "milk"] },
  { name: "Lemonade", price: 2.5, tags: ["cold"] },
];
const allTags = new Set<string>();
const countByTag = new Map<string, number>();
const priceByName: Record<string, number> = {};
for (const { name, price, tags } of menu) {
  priceByName[name] = price;
  for (const tag of tags) {
    allTags.add(tag);
    countByTag.set(tag, (countByTag.get(tag) || 0) + 1);
  }
}
console.log(`Tags: ${[...allTags].join(", ")}`);
for (const [tag, count] of countByTag) {
  console.log(`${tag}: ${count} items`);
}
console.log(priceByName);
const order: string[] = ["Latte", "Cocoa", "Latte"];
let total = 0;
for (const name of order) {
  total += priceByName[name];
}
console.log(`Order total: $${total.toFixed(2)}`);
for (const item of menu) {
  const note = item.note ? ` (${item.note})` : "";
  console.log(`$${item.price.toFixed(2).padStart(5)} ${item.name}${note}`);
}

npx tsc reports no errors, and node menu.ts shows:

Tags: hot, milk, cold
hot: 2 items
milk: 2 items
cold: 2 items
{ Latte: 3.5, 'Iced tea': 2.75, Cocoa: 3, Lemonade: 2.5 }
Order total: $10.00
$ 3.50 Latte
$ 2.75 Iced tea (seasonal)
$ 3.00 Cocoa
$ 2.50 Lemonade

Follow how each structure earns its place:

Lines What happens Idea
1–6 Item names the shape; note is optional and tags is an array inside each object 7.3–7.5
13–15 Three empty collections: a Set of tags, a Map of counts, a Record of prices 7.7–7.9
16 The loop header destructures each item into name, price, and tags 7.10
17 A Record because item names are strings and the lookup on line 31 uses a variable key 7.7
18–21 The inner loop (Day 5) adds each tag to the set, which ignores repeats, and counts it in the map 7.8, 7.9
23–26 The set is spread and joined; the map is looped as [tag, count] pairs 7.8, 7.9
30–32 Each name in the order looks up its price; priceByName[name] is number to the checker 7.7
35 item.note is string | undefined, so the conditional operator checks it before using it 7.4

Line 20 is the counting form from 7.8. Line 31 trusts that every ordered name is on the menu; if order held "Mocha", priceByName["Mocha"] would be undefined and total would become NaN, so a real program would check with === undefined first, as 7.7 showed. Try adding an item with a new tag, or a note to the latte, and see which lines of output change.

Wrap-up · 2 of 8

Common mistakes

Today’s messages and silent surprises in one place. The first group comes from npx tsc; the second shows no message at all.

Message or symptom Usual cause Fix
TS2339: Property 'author' does not exist on type ... Reading, adding, or destructuring a key that is not in the shape Put the key in the literal or the alias
TS2551 / TS2561: ... Did you mean 'title'? A misspelled key Use the suggested spelling
TS2322: Type 'string' is not assignable to type 'number'. Assigning the wrong kind of value to a property Match the property’s type
TS2741: Property 'pages' is missing in type ... A literal that leaves out a required property Add it, or make it optional with ?
TS2353: Object literal may only specify known properties ... A literal with a key the alias does not have Remove it, or add it to the alias
TS18048: 'novel.subtitle' is possibly 'undefined'. Using an optional property without checking it if (novel.subtitle) { ... }
TS2540: Cannot assign to 'isbn' because it is a read-only property. Assigning to a readonly property Set it in the literal only
TS2488: Type ... must have a '[Symbol.iterator]()' method ... for...of straight over an object Object.entries(obj)
TS7053: ... expression of type 'string' can't be used to index type ... A variable key on a fixed-shape object, or [0] on a Set Record<string, T>; [...set][0]
TS7052: ... Did you mean to call 'counts.get'? Brackets on a Map get and set
TS2532: Object is possibly 'undefined'. Arithmetic on map.get(key) (map.get(key) || 0) + 1
TypeError: Cannot read properties of undefined (reading 'title') Indexing an array of objects past the end Check length, or use for...of
A change shows up in a “copy” const copy = book; shares one object { ...book }
undefined from a Record A key that was never added === undefined or || 0
A set holds two “equal” objects Objects compare by reference Use strings or numbers as set values and map keys
A variable named string appears const { title: string } = book; renames const { title } = book;
Wrap-up · 3 of 8

Vocabulary

Term Definition Example
object One value that holds several named values { title: "Dune", pages: 412 }
property One key–value pair in an object pages: 412
key / value A property’s name / what it holds pages / 412
object literal Braces with key: value pairs that build an object { name: "Mochi", age: 5 }
dot notation Reading or changing a property with . book.pages = 416
bracket notation Reading or changing a property with the key as a string in [] cat["favorite toy"]
shorthand property { name } for { name: name } const dog = { name, age: 3 };
reference What a variable holds for an object: a link to it, so = shares, not copies const copy = book;
object type / shape The keys an object has and the type of each value { title: string; pages: number; }
type alias A declaration that names a type type Book = { title: string; pages: number }
optional property A property a literal may leave out; reading it then gives undefined subtitle?: string
readonly property A property that can be set only in the literal readonly isbn: string
nested object An object stored as another object’s property dune.author.name
index signature A rule in a type that allows any key of some type What Record provides
dictionary An object used to look values up by string keys added at run time Record<string, number>
Map A collection of key–value pairs with set, get, has, delete, size new Map<string, number>()
Set A collection of values with no duplicates new Set(tags)
object destructuring Declaring variables from properties by name const { title, pages } = book;
Wrap-up · 4 of 8

Summary

  • An object literal groups named values: { title: "Dune", pages: 412 }. Read and change properties with book.pages or book["pages"]; const fixes which object the name refers to, not its contents, and = shares an object rather than copying it.
  • The checker learns an object’s shape from the literal and rejects unknown keys (TS2339), wrong value types (TS2322), and literals that miss (TS2741) or add (TS2353) properties. A type alias, type Book = { ... }, names a shape for reuse; ? makes a property optional, so it reads as string | undefined and must be checked, and readonly forbids assignment.
  • Properties can hold objects and arrays (dune.author.name), and arrays can hold objects (Book[]), where every Day 5 loop pattern works.
  • An object cannot be looped directly: Object.keys, Object.values, and Object.entries give arrays, and for (const [key, value] of Object.entries(obj)) visits every property.
  • Record<string, number> is a dictionary with string keys added at run time; Map<K, V> does the same job with methods, any key type, size, and a get the checker knows may give undefined; Set<T> holds each value once and answers “is this in?”
  • const { title, pages } = book; pulls properties into variables by name, with key: newName to rename and key = default for missing ones, including in a for...of header.
Wrap-up · 5 of 8

Practice

Do these in your day07 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as unknown-property.ts, wrong-type-property.ts, missing-property.ts, extra-property.ts, subtitle-length.ts, readonly-isbn.ts, loop-over-object.ts, variable-key.ts, map-bracket.ts, set-index.ts, destructure-missing.ts, or the questions’ predict-shape.ts and student-wrong.ts), fix it or delete it. Then type each program yourself, check it with npx tsc, run it with node, and only then open the answer. Change the starting values and run them again.

Question 15 · Short answer

Word count. Store a sentence in a constant (it stands for any sentence, so annotate it). Count how often each word appears, using a Map<string, number>, then print one line per word with its count, and finally how many different words there were. Treat capital and small letters as the same word.

Check your reasoning

One possible solution:

word-count.ts
const sentence: string = "the cat saw the dog and the dog saw the cat";
const counts = new Map<string, number>();
for (const word of sentence.toLowerCase().split(" ")) {
  counts.set(word, (counts.get(word) || 0) + 1);
}
for (const [word, count] of counts) {
  console.log(`${word}: ${count}`);
}
console.log(`${counts.size} different words`);
the: 4
cat: 2
saw: 2
dog: 2
and: 1
5 different words

Day 3’s toLowerCase() and split(" ") turn the sentence into an array of words. For each word, line 4 is the counting form from 7.8: counts.get(word) is undefined the first time, so || 0 starts the count at 0, and set stores one more than before. The map keeps the words in first-seen order, so the loop on line 6 prints them that way, and size is the number of different words. Try a sentence with punctuation, such as "Stop. Stop!", and notice that "stop." and "stop!" count as different words; Day 3’s replaceAll can strip the marks first.

Reread 7.8 Map if your result differed.

Question 16 · Short answer

Invert a phone book. Start from a Record<string, string> that maps names to phone numbers. Build a second Record<string, string> that maps each number back to its name, print it, and use it to look up who is calling from a number stored in a variable. Also show what the lookup gives for a number that is not in the book.

Check your reasoning

One possible solution:

invert-phone-book.ts
const phoneBook: Record<string, string> = {
  Ana: "555-0101",
  Ben: "555-0199",
  Cleo: "555-0142",
};
const byNumber: Record<string, string> = {};
for (const [name, number] of Object.entries(phoneBook)) {
  byNumber[number] = name;
}
console.log(byNumber);
const caller: string = "555-0199";
console.log(`Call from ${byNumber[caller]}`);
console.log(byNumber["555-0000"]);
{ '555-0101': 'Ana', '555-0199': 'Ben', '555-0142': 'Cleo' }
Call from Ben
undefined

Line 7 loops over the pairs from Object.entries, destructuring each into name and number, and line 8 stores them the other way round: the number is now the key. Node prints the keys in quotes because they contain dashes. Line 11 looks up a key held in a variable, which only a Record (or a Map) allows. Line 13 shows the gap from 7.7: a number that was never added gives undefined, and a real program would check for that before printing. If two people shared a number, the second would overwrite the first; a Record<string, string[]> would keep both.

Reread 7.7 Record for Dictionary-Shaped Data and 7.6 Object.keys, Object.values, and Object.entries if your result differed.

Question 17 · Short answer

Common elements. Store two arrays of numbers, each possibly containing repeats. Using a Set, print the values that appear in both arrays, each once, and how many there are.

Check your reasoning

One possible solution:

common-elements.ts
const mine: number[] = [3, 7, 11, 7, 20, 5];
const yours: number[] = [5, 7, 8, 20, 20];
const yourSet = new Set(yours);
const common = new Set<number>();
for (const value of mine) {
  if (yourSet.has(value)) {
    common.add(value);
  }
}
console.log([...common]);
console.log(common.size);
[ 7, 20, 5 ]
3

Line 3 turns the second array into a set, so line 6 can ask has instead of searching with includes each time. Line 7 adds matches to a second set, which is what makes each common value appear once even though 7 is in mine twice and 20 is in yours twice. Line 10 spreads the result into an array in the order the values were found in mine. Swap the two arrays and the order of the output changes but not its contents.

Reread 7.9 Set if your result differed.

Wrap-up · 6 of 8

Review questions

Question 18 · Tracing

Predict exactly what this program shows. Think about which objects are shared.

review-shared.ts
type Account = {
  owner: string;
  balance: number;
  card: { last4: string; active: boolean };
};
const main: Account = {
  owner: "Ana",
  balance: 120,
  card: { last4: "4242", active: true },
};
const joint = { ...main };
joint.balance = 50;
joint.card.active = false;
const { balance, card } = main;
console.log(balance, card.active);
console.log(joint.owner === main.owner, joint.card === main.card);
Check your reasoning
120 false
true true

Line 11 spreads main into a new object, so joint is a different outer object: line 12 changes only joint.balance, and main.balance is still 120. But spreading copies each property’s value, and the value of card is a reference to the inner object, so joint.card and main.card are the same object. Line 13 therefore changes the one card that both share, and line 15 shows card.active as false through main. Line 16: the two owner strings are equal, and the two card references point at the same object, so both comparisons are true. A spread copy is one level deep.

Reread 7.1 Object Literals and Dot Access and 7.5 Nested Objects and Arrays of Objects if your output differed.

Question 19 · Debugging

Rosa’s program should print each course and its room. npx tsc rejects it. Predict the message, explain it, and write the fix so that a course with no room prints something sensible.

review-optional.ts
type Course = {
  code: string;
  room?: string;
};
const courses: Course[] = [
  { code: "CS101", room: "B204" },
  { code: "ART110" },
];
for (const course of courses) {
  console.log(`${course.code} in room ${course.room.toUpperCase()}`);
}
Check your reasoning
review-optional.ts:10:41 - error TS18048: 'course.room' is possibly 'undefined'.

room is optional, so for ART110 it is undefined, and undefined.toUpperCase() would be the runtime error from Day 3. The checker reports the risk at column 41, where toUpperCase is called. The fix checks the property first; inside the if block the checker knows it is a string:

review-optional-fixed.ts
type Course = {
  code: string;
  room?: string;
};
const courses: Course[] = [
  { code: "CS101", room: "B204" },
  { code: "ART110" },
];
for (const course of courses) {
  if (course.room) {
    console.log(`${course.code} in room ${course.room.toUpperCase()}`);
  } else {
    console.log(`${course.code}: room to be announced`);
  }
}
CS101 in room B204
ART110: room to be announced

If you typed the original program, fix or delete it before you go on.

Reread 7.4 Optional and Readonly Properties if you missed it.

Question 20 · Tracing

Predict exactly what this program shows.

review-tally.ts
const votes: string[] = ["tea", "coffee", "tea", "juice", "tea", "coffee"];
const tally: Record<string, number> = {};
for (const vote of votes) {
  tally[vote] = (tally[vote] || 0) + 1;
}
const drinks = new Set(votes);
console.log(drinks.size === Object.keys(tally).length);
let winner = "";
for (const [drink, count] of Object.entries(tally)) {
  if (winner === "" || count > tally[winner]) {
    winner = drink;
  }
}
console.log(`${winner} wins with ${tally[winner]} votes`);
console.log(Object.values(tally));
Check your reasoning
true
tea wins with 3 votes
[ 3, 2, 1 ]
  • Lines 3 to 5 count with the || 0 form: tally ends as { tea: 3, coffee: 2, juice: 1 }, keys in first-seen order.
  • Line 6 makes a set of the votes, which has 3 values, and Object.keys(tally) has 3 keys: true. Both are ways of counting the different drinks.
  • Lines 9 to 13: for tea, winner === "" is true, so short-circuiting never looks up tally[""], and winner becomes "tea". For coffee, 2 > 3 is false. For juice, 1 > 3 is false.
  • Line 15: the values in key order.

Reread 7.7 Record for Dictionary-Shaped Data and 7.9 Set if any line differed.

Question 21 · Tracing

Predict exactly what this program shows. One line is a trap you met on Day 4.

review-grades.ts
type Student = {
  name: string;
  scores: number[];
};
const students: Student[] = [
  { name: "Ana", scores: [90, 80] },
  { name: "Ben", scores: [] },
  { name: "Cleo", scores: [70] },
];
const totals = new Map<string, number>();
for (const { name, scores } of students) {
  let total = 0;
  for (const score of scores) {
    total += score;
  }
  totals.set(name, total);
}
console.log(totals);
console.log(totals.get("Ben") || "no scores");
console.log(totals.get("Dan") || "no scores");
console.log(totals.has("Ben"), totals.size);
Check your reasoning
Map(3) { 'Ana' => 170, 'Ben' => 0, 'Cleo' => 70 }
no scores
no scores
true 3
  • Lines 11 to 17 destructure each Student and sum the inner array. Ben’s array is empty, so his total is 0, and line 16 stores it: the map has three entries.
  • Line 19 is the trap: totals.get("Ben") is 0, which is falsy, so || gives "no scores" even though Ben is in the map. Day 4’s volume example made the same mistake; || cannot tell 0 from “missing.”
  • Line 20: "Dan" really is missing, so get gives undefined and the result is "no scores" again. The two lines look the same for different reasons.
  • Line 21: has("Ben") is true, which is the right way to ask whether a key is present, and size is 3.

Reread 7.8 Map if any line differed.

Question 22 · Short answer

A program keeps track of library members. Each member has a name, a join year, and sometimes an email address. The program also needs to look up a member’s overdue-book count by their membership number (a number), and keep the set of book titles that are currently out on loan. Say which of today’s structures you would use for each of the three pieces, and why.

Check your reasoning

Model answer: A member is a plain object described by a type alias, type Member = { name: string; joinYear: number; email?: string }, because its keys are fixed and known in advance, they hold different types, and email is sometimes missing, which ? expresses. The overdue counts are a Map<number, number>, because the keys are membership numbers, which are numbers, and a Record only has string keys; get and has look up a count safely. The titles on loan are a Set<string>, because each title is either out or not, no value is attached, and a set stores each title once and answers has directly.

A complete answer must:

  • choose a type alias for the member and give the reason: fixed keys of different types, one optional,
  • choose a Map for the counts and mention that its keys can be numbers (or that get handles a missing key), and
  • choose a Set for the titles because only membership matters and there are no duplicates.

Reread the comparison table in 7.8 Map and 7.9 Set if your reasoning differed.

Question 23 · Multiple choice

const book = { title: "Dune", pages: 412 }; Which statement prints every key and value of book, one property per line?

  1. for (const [key, value] of book) { console.log(key, value); }
  2. for (const [key, value] of Object.entries(book)) { console.log(key, value); }
  3. for (const key of Object.keys(book)) { console.log(key, book.key); }
  4. const { key, value } = book; console.log(key, value);
Check your reasoning

B. Object.entries gives the properties as [key, value] pairs in an array, which for...of can loop over, destructuring each pair.

  • A is wrong: an object cannot be looped with for...of directly (TS2488).
  • C is wrong: book.key looks for a property literally named key, which does not exist (TS2339); it would need book[key], which 7.7 showed is rejected for a variable key on a fixed shape.
  • D is wrong: destructuring pulls out properties named key and value, which book does not have (TS2339), and it is not a loop.

Reread 7.6 Object.keys, Object.values, and Object.entries and 7.10 Object Destructuring if you chose differently.

Wrap-up · 7 of 8

Go further

The Handbook’s page on object types covers everything from today’s aliases to optional and readonly properties, and MDN’s guides go deeper on objects and on the keyed collections: TypeScript Handbook: Object Types, MDN: Working with objects, and MDN: Keyed collections.

Wrap-up · 8 of 8

Reflection

Check each statement. If the answer is “not yet,” reread the linked subsection.

  • I can build an object literal, read and change its properties, and explain why two names can share one object. Reread
  • I can predict which property mistakes the checker reports, and read a TS2339 or TS2322 message about a property. Reread
  • I can name a shape with a type alias and use it as an annotation. Reread
  • I can declare optional and readonly properties and check an optional one before using it. Reread
  • I can reach into nested objects with chained dots and loop over an array of objects. Reread
  • I can loop over an object with Object.keys, Object.values, or Object.entries. Reread
  • I can use a Record to count or look up values by string keys added at run time. Reread
  • I can use a Map with set, get, has, delete, and size, and loop over its pairs. Reread
  • I can use a Set to remove duplicates or answer "is this in?" Reread
  • I can pull properties out of an object by name with destructuring, including in a for...of header. Reread