Skip to content
HopperHopper

Course navigation

Phase 3 · Real programsDay 15

Classes

  • About 70 minutes
  • 8 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 70 minutes

By the end you will be able to

  1. Write a class with fields, a constructor, and methods, create objects from it with new, and explain what this refers to inside a method.
  2. Keep an object's data valid with private fields, readonly fields, and getters, so outside code can read a value but change it only through methods that check it.
  3. Make a class implement an interface, extend a class with extends and super, override a method, and use static members that belong to the class itself.
  4. Decide whether a class or plain objects and functions are the better tool for a job.

What to remember from earlier

Section 1 of 8

15.1 Classes, Constructors, and new

Before you start, set up a new project folder named day15 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, one file per program, checked with npx tsc and run with node.

Suppose a library program needs fifty book records. Since Day 7 you would describe the shape once, with an interface, and then write fifty object literals, each spelling out title: and pages: again. Nothing stops one of those literals from misspelling a property, and nothing gives every book a starting value you forgot to type. What you want is a template that you write once and then stamp out objects from, each one filled in the same way. That template is a class.

A class is a blueprint for making objects: it lists the properties every object made from it will have, and the code that fills them in. Each object made from a class is called an instance of the class. The analogy is a cookie cutter: the cutter is the class, each cookie is an instance, and every cookie has the same shape but its own dough. (Where the analogy stops: a class can also give its objects functions to call, as 15.2 shows.)

You have used built-in classes already. On Day 7, new Map<string, number>() made a new, empty map: Map is a class built into JavaScript, and new made an instance of it. Today you write your own.

Worked example: A Book class

Read the class first, lines 1 to 9, then watch lines 11 and 12 use it.

book-class.ts
class Book {
  title: string;
  pages: number;

  constructor(title: string, pages: number) {
    this.title = title;
    this.pages = pages;
  }
}

const atlas = new Book("Atlas", 240);
const poems = new Book("Poems", 96);

console.log(atlas.title);
console.log(poems.pages);
console.log(atlas);
console.log(atlas.pages + poems.pages);
Atlas
96
Book { title: 'Atlas', pages: 240 }
336
Line What happens
1 class Book starts the class. Its name is PascalCase, like an interface’s
2–3 Two fields: every Book will have a title string and a pages number. Like an interface’s properties, but with no values yet
5 The constructor: the function that runs once for each new book, to fill in its fields. Its parameters are what you pass in
6–7 this means “the new object being built”. this.title = title stores the parameter title in the new object’s title field
11 new Book("Atlas", 240) makes an empty object, runs the constructor with title as "Atlas" and pages as 240, and gives back the filled object
12 A second, separate object; its constructor run stores different values
14–15 Each instance’s fields are read with a dot, exactly like an object literal’s properties
16 console.log shows an instance with its class name in front: Book { ... }

Take the syntax apart:

class Name {
  field: type;

  constructor(parameter: type) {
    this.field = parameter;
  }
}
Piece What it is
class Name { ... } Declares the class. Unlike interface, a class is real code: node keeps it and runs it
field: type; A field (also called a property): a value each instance stores, with its type for the checker
constructor(...) {...} The constructor, a special function with the fixed name constructor, run once by new for each instance
this.field = ... Inside the class, this is the instance being worked on; this.field is that instance’s field
new Name(arguments) Makes a new instance: the arguments go to the constructor’s parameters

The name title appears twice on line 6, and they are different things. this.title is the field on the new object; plain title is the constructor’s parameter, a local variable that disappears when the constructor finishes, as Day 8 taught. The constructor’s job is to copy the parameters into fields so they outlive the call.

A class is also a type. After class Book, you can write const atlas: Book, a parameter book: Book, or a Book[], and the checker knows that a Book has a title string and a pages number. One declaration gives you both the blueprint that node runs and the description the checker uses.

Now vary it. A field can be given a starting value right where it is declared, and a constructor parameter can have a default value, as on Day 8:

library-card.ts
class LibraryCard {
  owner: string;
  limit: number;
  borrowed = 0;

  constructor(owner: string, limit = 5) {
    this.owner = owner;
    this.limit = limit;
  }
}

const ana = new LibraryCard("Ana");
const ben = new LibraryCard("Ben", 2);

ana.borrowed = 3;

console.log(ana);
console.log(ben);
console.log(ana.limit - ana.borrowed);
LibraryCard { owner: 'Ana', limit: 5, borrowed: 3 }
LibraryCard { owner: 'Ben', limit: 2, borrowed: 0 }
2

Line 4, borrowed = 0, is a field initializer: every new card starts with 0 borrowed, so the constructor does not need to set it, and the checker infers the type number from the 0. Line 12 leaves out the limit, so limit takes its default of 5; line 13 passes 2. Line 15 changes one field of one instance: ana.borrowed becomes 3, while ben.borrowed is still 0. Each instance has its own copy of every field.

Key idea

A class is a blueprint: its fields list what every instance stores, and its constructor fills them in. new Name(arguments) makes a fresh instance and runs the constructor on it, with this meaning that new instance. The class name is also a type.

Watch out

Forgetting new. A class is not an ordinary function; it can only be called with new:

forget-new.ts
class Book {
  title: string;

  constructor(title: string) {
    this.title = title;
  }
}

const atlas = Book("Atlas");
console.log(atlas.title);
forget-new.ts:9:15 - error TS2348: Value of type 'typeof Book' is not callable. Did you mean to include 'new'?

The checker even suggests the fix. If you ran the program anyway, node would stop with TypeError: Class constructor Book cannot be invoked without 'new'. Write new Book("Atlas"), then fix or delete the file before your next check.

A field the constructor never fills. Strict mode checks that every field gets a value, either from an initializer or in the constructor:

missing-field.ts
class Song {
  title: string;
  seconds: number;

  constructor(title: string) {
    this.title = title;
  }
}

const song = new Song("Rain");
console.log(song.seconds);
missing-field.ts:3:3 - error TS2564: Property 'seconds' has no initializer and is not definitely assigned in the constructor.

A Song would claim to have a seconds number but actually hold undefined, and song.seconds would show undefined at run time. Fix it in one of three ways: add a constructor parameter and this.seconds = seconds;, give the field an initializer such as seconds = 0;, or make it optional with seconds?: number; if a song really may lack one. Then fix or delete the file.

Pause and try

Question 1 · Tracing

Predict exactly what this program shows.

predict-class.ts
class Ticket {
  seat: string;
  price: number;
  used = false;

  constructor(seat: string, price = 12) {
    this.seat = seat;
    this.price = price;
  }
}

const first = new Ticket("A4");
const second = new Ticket("B9", 15);
second.used = true;

console.log(first.price + second.price);
console.log(first.used);
console.log(second);
Check your reasoning
27
false
Ticket { seat: 'B9', price: 15, used: true }
  • Line 12: no price is passed, so the default makes first.price 12. Line 13 passes 15.
  • Line 16: 12 + 15 is 27.
  • Line 17: every ticket starts with used = false from line 4. Line 14 changed only second, so first.used is still false.
  • Line 18: console.log shows the class name and every field of second, in the order the fields were declared.

Reread 15.1 Classes, Constructors, and new if any line differed.

Question 2 · Multiple choice

After class Book { ... } from book-class.ts, what does new Book("Atlas", 240) do?

  1. It changes the class Book so that its title is now "Atlas".
  2. It makes a new object, runs the constructor with this as that object, and gives the object back.
  3. It calls the constructor like an ordinary function and gives back undefined, because the constructor has no return.
  4. It only tells the checker about a new type; node skips it.
Check your reasoning

B. new creates a fresh instance, runs the constructor on it so the fields are filled in, and the whole new expression has that instance as its value.

  • A is wrong: the class is the blueprint and never changes. Each new makes a separate instance with its own fields; poems is unaffected by atlas.
  • C is wrong: a constructor does not need return; new gives back the instance automatically.
  • D is wrong: unlike an interface, a class is real code that node keeps, and new runs at run time.

Reread 15.1 Classes, Constructors, and new if you chose differently.

Section 2 of 8

15.2 Methods and this

On Day 10 you put functions in an object’s properties and called them with a dot: formatter.format(19.5). A class can do the same for every instance at once. A method is a function declared inside a class; every instance can call it, and inside it, this is the instance it was called on. That is the point of a class: the data and the code that works on that data live together.

Worked example: A shopping cart

cart-class.ts
class Cart {
  items: string[] = [];
  total = 0;

  add(name: string, price: number): void {
    this.items.push(name);
    this.total += price;
  }

  describe(): string {
    return `${this.items.length} items, $${this.total.toFixed(2)}`;
  }
}

const mine = new Cart();
const yours = new Cart();

mine.add("bread", 3.5);
mine.add("milk", 1.25);
mine.add("eggs", 2.75);
yours.add("apples", 4);
yours.add("pears", 2.5);

console.log(mine.describe());
console.log(yours.describe());
console.log(mine.items);
3 items, $7.50
2 items, $6.50
[ 'bread', 'milk', 'eggs' ]

A method is written like Day 10’s method shorthand: name, parameters, return type, body, with no function keyword and no =>. This class has no constructor at all: both fields have initializers, so there is nothing to fill in, and new Cart() takes no arguments.

Line Call this is mine.items mine.total yours.total
15 new Cart() [] 0
16 new Cart() [] 0 0
18 mine.add("bread", 3.5) mine ['bread'] 3.5 0
19 mine.add("milk", 1.25) mine ['bread', 'milk'] 4.75 0
20 mine.add("eggs", 2.75) mine ['bread', 'milk', 'eggs'] 7.5 0
21 yours.add("apples", 4) yours unchanged 7.5 4
22 yours.add("pears", 2.5) yours unchanged 7.5 6.5

There is only one add method, written once on line 5, yet line 18 changes mine and line 21 changes yours. The rule: this is the object before the dot. In mine.add(...), this is mine, so line 7’s this.total += price adds to mine.total. Line 24’s describe reads mine’s fields; line 25’s reads yours’s.

Now vary it: a method can call another method of the same instance, again through this.

cart-methods.ts
class Cart {
  items: string[] = [];
  total = 0;

  add(name: string, price: number): void {
    this.items.push(name);
    this.total += price;
  }

  isEmpty(): boolean {
    return this.items.length === 0;
  }

  describe(): string {
    if (this.isEmpty()) {
      return "empty cart";
    }
    return `${this.items.join(", ")}: $${this.total.toFixed(2)}`;
  }
}

const cart = new Cart();
console.log(cart.describe());
cart.add("bread", 3.5);
cart.add("milk", 1.25);
console.log(cart.describe());
empty cart
bread, milk: $4.75

Line 15 calls this.isEmpty(). Inside describe, this is cart, so this.isEmpty() asks cart whether it is empty, and isEmpty’s own this is cart too. On line 23 the cart has no items, so describe returns early with "empty cart", Day 8’s return-early pattern. After two add calls, line 26 joins the item names with join, which Day 3 previewed: it glues an array’s strings together with the separator between them.

Key idea

A method is a function declared inside a class, written name(parameters): type { ... }. Inside it, this is the object before the dot in the call, so one method written once works on whichever instance calls it. Inside a class, every field and method is reached through this.

Watch out

Leaving out this. Inside a method, a field’s name alone is not a variable:

forgot-this.ts
class Cart {
  total = 0;

  add(price: number): void {
    total += price;
  }
}

const cart = new Cart();
cart.add(4);
console.log(cart.total);
forgot-this.ts:5:5 - error TS2663: Cannot find name 'total'. Did you mean the instance member 'this.total'?

A method can run on many instances, so a bare total would not say whose total. The checker suggests this.total, which says “the total of the object this method was called on.” At run time the original would stop with ReferenceError: total is not defined. Fix it, then fix or delete the file.

Taking a method off its object. this is decided by the dot at the moment of the call, not where the method was written. Store the method in a variable and call it without a dot, and there is no object before the dot:

lost-this.ts
class Cart {
  items: string[] = ["bread", "milk"];

  describe(): string {
    return `${this.items.length} items`;
  }
}

const cart = new Cart();
console.log(cart.describe());

const later = cart.describe;
console.log(later());
2 items
TypeError: Cannot read properties of undefined (reading 'items')

The checker accepts this program, but it crashes at run time. Line 10 calls cart.describe(), so this is cart: 2 items. Line 12 copies the method itself (no parentheses, so it is not called) into later. Line 13 calls later() with nothing before a dot, so inside describe, this is undefined, and this.items reads a property of undefined. The same thing happens when you pass cart.describe as a callback, as Day 10 taught you to pass functions. The fix is to wrap the call in an arrow function, which keeps the dot:

kept-this.ts
class Cart {
  items: string[] = ["bread", "milk"];

  describe(): string {
    return `${this.items.length} items`;
  }
}

const cart = new Cart();
const later = () => cart.describe();
console.log(later());
2 items

later is now an arrow function whose body is cart.describe(), so whenever it runs, cart is before the dot.

Pause and try

Question 3 · Tracing

Predict exactly what this program shows. Keep the two counters’ fields separate.

predict-this.ts
class Counter {
  label: string;
  count = 0;

  constructor(label: string) {
    this.label = label;
  }

  up(by = 1): number {
    this.count += by;
    return this.count;
  }

  show(): string {
    return `${this.label}: ${this.count}`;
  }
}

const laps = new Counter("laps");
const goals = new Counter("goals");

laps.up();
goals.up(2);
console.log(laps.up(3));
console.log(goals.show());
console.log(laps.show());
Check your reasoning
4
goals: 2
laps: 4
Line Call laps.count goals.count Shown
22 laps.up() 1 0
23 goals.up(2) 1 2
24 laps.up(3) 4 2 4
25 goals.show() 4 2 goals: 2
26 laps.show() 4 2 laps: 4

Line 22 passes no argument, so by takes its default of 1. Each call’s this is the object before the dot, so goals.up(2) never touches laps.count. Line 24 shows what up returns, the new count.

Reread 15.2 Methods and this if any line differed.

Question 4 · Multiple choice

cart is a Cart from lost-this.ts. Which line shows 2 items instead of crashing?

  1. const f = cart.describe; console.log(f());
  2. const f = () => cart.describe(); console.log(f());
  3. const f = describe; console.log(f());
  4. console.log(Cart.describe());
Check your reasoning

B. The arrow function’s body calls cart.describe() with cart before the dot, so this is cart when describe runs.

  • A is wrong: f() has no object before a dot, so this is undefined and this.items crashes with a TypeError. The checker does not catch it.
  • C is wrong: there is no variable named describe; a method is reached only through an instance, so the checker reports Cannot find name 'describe'.
  • D is wrong: describe belongs to each instance, not to the class name itself; the checker rejects Cart.describe. (Members that do belong to the class name are the subject of 15.7.)

Reread 15.2 Methods and this if you chose differently.

Section 3 of 8

15.3 Private Fields and readonly

ana.borrowed = 3 on line 15 of library-card.ts worked, and so would ana.borrowed = -40, or cart.total = 0 while the cart still holds three items. Any line anywhere in the program can put an instance’s fields into a state that makes no sense. A class can prevent that: it can keep a field to itself, so the only way to change it is through a method that checks the new value first.

On Day 10 you got the same protection from a closure: makeCounter’s count was a local variable that only the returned functions could reach, which Day 10 called private state. A class has syntax for it.

A private field is a field whose name starts with #. It can be read and changed only by code inside the class’s braces; anywhere else, the name does not exist. The # is part of the name: you write #target when you declare it and this.#target when you use it. This is JavaScript itself, not just the checker: node enforces it too.

A readonly field is a field marked readonly. The constructor may set it, once, and after that nobody can assign to it, not even the class’s own methods. It is the same readonly you put on object properties on Day 7, and like that one, it is a checker-only rule.

Worked example: A thermostat that keeps its target sensible

thermostat.ts
class Thermostat {
  readonly room: string;
  #target = 20;

  constructor(room: string) {
    this.room = room;
  }

  setTarget(celsius: number): boolean {
    if (celsius < 10 || celsius > 30) {
      return false;
    }
    this.#target = celsius;
    return true;
  }

  describe(): string {
    return `${this.room}: ${this.#target}°C`;
  }
}

const hall = new Thermostat("Hall");
console.log(hall.setTarget(22));
console.log(hall.setTarget(95));
console.log(hall.describe());
console.log(hall);
true
false
Hall: 22°C
Thermostat { room: 'Hall' }
Line What happens
2 readonly room: set once by the constructor on line 6, then fixed. A thermostat does not move to another room
3 #target = 20: a private field with a starting value. Only code inside these braces can see it
9–15 setTarget is the only way to change the target. It refuses anything below 10 or above 30 and reports whether it accepted the value
23 22 is in range: line 13 stores it and the method returns true
24 95 is out of range: line 11 returns false and the target stays 22
25 describe is inside the class, so it may read this.#target
26 console.log shows only room. Private fields are hidden even from it

Because #target can be changed only on line 13, and line 13 runs only after the check on line 10, the target is always between 10 and 30. No code outside the class can break that rule, however it is written. A rule like this, which is true of an object at every moment, is what people mean by keeping an object’s data valid.

Compare the class with Day 10’s closure version. The counter below works exactly like makeCounter: two independent counts, each changed only through increment.

class-counter.ts
class Counter {
  #count = 0;

  increment(): number {
    this.#count += 1;
    return this.#count;
  }

  value(): number {
    return this.#count;
  }
}

const clicks = new Counter();
const visits = new Counter();

clicks.increment();
clicks.increment();
visits.increment();

console.log(clicks.value());
console.log(visits.value());
2
1

Each new Counter() makes an instance with its own #count, just as each makeCounter() call made its own count variable. The class version needs no interface for the result and no factory function: the class is the type, and new is the factory.

You may meet a second way of writing private fields in other people’s code: the word private in front of an ordinary name, as in private target = 20. That is a checker-only rule, like readonly: npx tsc refuses outside access, but node lets it happen and console.log shows the field. This course uses #, which both of them enforce.

Key idea

A #name field is private: only code inside the class can read or change it, so every change goes through a method that can check it first. A readonly field is set once, in the constructor or its initializer, and never assigned again. Together they let a class guarantee its data stays valid.

Watch out

Reaching a private field from outside.

private-outside.ts
class Thermostat {
  #target = 20;

  describe(): string {
    return `${this.#target}°C`;
  }
}

const hall = new Thermostat();
hall.#target = 95;
console.log(hall.describe());
private-outside.ts:10:6 - error TS18013: Property '#target' is not accessible outside class 'Thermostat' because it has a private identifier.

Line 10 is outside the class’s braces, so #target cannot be reached there. This one is not only the checker’s rule: node refuses to even start the program, with SyntaxError: Private field '#target' must be declared in an enclosing class. Use the method the class offers, setTarget, which may say no. Fix or delete the file.

Assigning a readonly field after construction.

readonly-assign.ts
class Thermostat {
  readonly room: string;

  constructor(room: string) {
    this.room = room;
  }
}

const hall = new Thermostat("Hall");
hall.room = "Kitchen";
readonly-assign.ts:10:6 - error TS2540: Cannot assign to 'room' because it is a read-only property.

Only the constructor may set room. If a thermostat really can move, drop readonly, or better, make the field private and add a method that moves it. Fix or delete the file.

Pause and try

Question 5 · Tracing

Predict exactly what this program shows. Math.min gives back the smaller of its arguments.

predict-private.ts
class Gauge {
  readonly unit: string;
  #level = 0;

  constructor(unit: string) {
    this.unit = unit;
  }

  fill(amount: number): void {
    if (amount <= 0) {
      return;
    }
    this.#level = Math.min(this.#level + amount, 100);
  }

  reading(): string {
    return `${this.#level}${this.unit}`;
  }
}

const tank = new Gauge("%");
tank.fill(60);
tank.fill(-20);
console.log(tank.reading());
tank.fill(55);
console.log(tank.reading());
Check your reasoning
60%
100%
  • Line 22: 60 is positive, so #level becomes Math.min(0 + 60, 100), which is 60.
  • Line 23: -20 is not positive, so line 11 returns before anything changes. #level stays 60.
  • Line 24: 60%. unit is "%", and the template literal puts the two side by side.
  • Line 25: Math.min(60 + 55, 100) is Math.min(115, 100), which is 100. The gauge never goes above 100.
  • Line 26: 100%.

The only code that changes #level is line 13, and it never stores a value above 100, so the level stays between 0 and 100 no matter what the rest of the program passes in.

Reread 15.3 Private Fields and readonly if any line differed.

Question 6 · Multiple choice

A Student class should let the program set a student’s id once when the student is created and never again, and should keep a list of grades that outside code can change only through addGrade, which rejects numbers outside 0 to 100. Which fields fit?

  1. id: number; and grades: number[] = [];
  2. readonly id: number; and #grades: number[] = [];
  3. #id: number; and readonly grades: number[] = [];
  4. readonly id: number; and readonly grades: number[] = [];
Check your reasoning

B. readonly matches “set once, never again,” and a private #grades means the only way to change the list is a method inside the class, such as addGrade, which can check each number.

  • A is wrong: with neither, outside code could assign a new id and push 500 into grades.
  • C is wrong: #id would hide the id from outside code entirely, though nothing said it should be secret; and readonly grades stops only reassigning the field. The array it holds can still be changed with student.grades.push(500), skipping addGrade’s check.
  • D is wrong for the same reason: readonly on grades protects the field, not the array inside it.

Reread 15.3 Private Fields and readonly if you chose differently.

Section 4 of 8

15.4 Getters

A private field is safe, but now outside code cannot even read it. thermostat.ts worked around that with a describe method, and class-counter.ts with a value() method. That works, but counter.value() reads like an action, when all you want is a value, the way items.length is a value with no parentheses.

A getter is a method that is used like a field. It is written with the word get in front of the method’s name and takes no parameters; reading object.name, with no parentheses, runs the method and gives back what it returns.

Worked example: A playlist that reports its size

playlist.ts
class Playlist {
  #songs: string[] = [];
  #seconds = 0;

  add(title: string, seconds: number): void {
    this.#songs.push(title);
    this.#seconds += seconds;
  }

  get count(): number {
    return this.#songs.length;
  }

  get length(): string {
    const minutes = Math.floor(this.#seconds / 60);
    const rest = this.#seconds % 60;
    return `${minutes}:${String(rest).padStart(2, "0")}`;
  }
}

const road = new Playlist();
console.log(road.count);
road.add("Rain", 185);
road.add("Lights", 222);
console.log(road.count);
console.log(road.length);
0
2
6:47
Line What happens
2–3 Two private fields: the titles and the total playing time in seconds
10–12 get count() is a getter. Outside the class it looks like a number field named count
22 road.count with no parentheses runs lines 10 to 12. The list is empty: 0
23–24 add is the only way in. 185 + 222 is 407 seconds
25 count is worked out again, from the list as it is now: 2
26 get length() turns 407 seconds into minutes and seconds: Math.floor(407 / 60) is 6 and 407 % 60 is 47, padded to two digits: 6:47

A getter is not a stored value. It runs every time it is read, so it is never out of date: count is always the list’s current length, and nobody has to remember to update a separate counter.

There is no set partner here, and that is deliberate. A property with only a getter is read-only from outside: code can read road.count but not assign to it. A private field plus a getter is the usual way to say “anyone may look, but only the class may change it.”

Now vary the field’s type. On Day 14 you wrote generic functions and interfaces with a type parameter such as <T>. A class can take a type parameter the same way, written after its name, and then use T for its fields and methods:

queue.ts
class Queue<T> {
  #items: T[] = [];

  join(item: T): void {
    this.#items.push(item);
  }

  next(): T | undefined {
    return this.#items.shift();
  }

  get size(): number {
    return this.#items.length;
  }
}

const line = new Queue<string>();
line.join("Ana");
line.join("Ben");
console.log(line.next());
console.log(line.size);

const orders = new Queue<number>();
orders.join(101);
console.log(orders.next());
console.log(orders.next());
Ana
1
101
undefined

Queue<T> is a line of waiting items: join adds at the end, and next removes and gives back the front item with Day 6’s shift, which gives undefined when the array is empty; that is why next’s return type is T | undefined. Line 17 makes a Queue<string>, so in that instance T is string and line.join(42) would be rejected. Line 23 makes a separate Queue<number>. Its second next() on line 26 finds the queue empty: undefined. The getter size reports how many are waiting, without letting anyone change #items directly.

Key idea

get name(): type { ... } defines a getter: reading object.name, without parentheses, runs it and gives back its result, worked out fresh each time. A private field with a getter and no setter can be read from outside but changed only by the class’s methods.

Watch out

Calling a getter, or assigning to one. A getter looks like a field from outside, so use it like a read-only field:

getter-call.ts
class Playlist {
  #songs: string[] = ["Rain", "Lights"];

  get count(): number {
    return this.#songs.length;
  }
}

const road = new Playlist();
console.log(road.count());
road.count = 10;
getter-call.ts:10:18 - error TS6234: This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'?
  Type 'Number' has no call signatures.
getter-call.ts:11:6 - error TS2540: Cannot assign to 'count' because it is a read-only property.

On line 10, road.count is already the number 2, and () would try to call the number as if it were a function; at run time that is TypeError: road.count is not a function. Line 11 tries to store into a property that has only a getter. Drop the parentheses, delete line 11, and change the playlist through add instead. Fix or delete the file.

Pause and try

Question 7 · Tracing

Predict exactly what this program shows.

predict-getter.ts
class Rectangle {
  width: number;
  height: number;

  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }

  get area(): number {
    return this.width * this.height;
  }

  get isSquare(): boolean {
    return this.width === this.height;
  }
}

const tile = new Rectangle(3, 4);
console.log(tile.area);
tile.width = 4;
console.log(tile.area);
console.log(tile.isSquare);
Check your reasoning
12
16
true
  • Line 20: area runs its body: 3 × 4 is 12.
  • Line 21: width is an ordinary field, so it may be changed.
  • Line 22: the getter runs again with the new width: 4 × 4 is 16. A stored area field would still say 12; a getter is worked out each time it is read.
  • Line 23: width and height are both 4: true.

Reread 15.4 Getters if any line differed.

Question 8 · Multiple choice

Inside a class Wallet with a private field #cents = 0, which member lets outside code write wallet.dollars to read the amount in dollars, but rejects wallet.dollars = 5?

  1. dollars = this.#cents / 100;
  2. get dollars(): number { return this.#cents / 100; }
  3. dollars(): number { return this.#cents / 100; }
  4. readonly #dollars = 0;
Check your reasoning

B. A getter is read without parentheses, and with no setter beside it the checker rejects assignment with TS2540. It is worked out from #cents every time, so it is always current.

  • A is wrong: this field is worked out once, when the wallet is created (0), and never updates; it can also be assigned from outside.
  • C is wrong: a method has to be called as wallet.dollars(). Without parentheses, wallet.dollars is the function itself, not a number.
  • D is wrong: a # field cannot be read from outside at all, and it would hold a fixed 0.

Reread 15.4 Getters if you chose differently.

Section 5 of 8

15.5 implements an Interface

On Day 10 the checker matched objects against interfaces by shape. That still works for instances: a class whose instances have every property of an interface fits that interface, as this program shows.

shape-without-implements.ts
interface Payment {
  readonly amount: number;
  label(): string;
}

class Voucher {
  readonly amount = 5;

  label(): string {
    return "voucher";
  }
}

const paid: Payment = new Voucher();
console.log(paid.label());
voucher

Voucher never mentions Payment, but on line 14 the checker compares shapes: a Voucher has an amount number and a label() method that returns a string, so it fits.

The trouble is where a mistake would be reported. If Voucher misspelled label, the error would appear on line 14, where the voucher is used, or worse, much later in another file. When you write a class that is meant to fit an interface, you want the checker to check the class itself, right where it is written. That is what implements does.

class Name implements Interface promises that every instance of the class will have every property and method the interface lists. The checker holds the class to it. implements is a line for the checker only: node strips it, and it adds nothing to the class; you must still write every field and method yourself.

Worked example: Two ways to pay

payments.ts
interface Payment {
  readonly amount: number;
  label(): string;
}

class CardPayment implements Payment {
  readonly amount: number;
  readonly lastDigits: string;

  constructor(amount: number, lastDigits: string) {
    this.amount = amount;
    this.lastDigits = lastDigits;
  }

  label(): string {
    return `card ending ${this.lastDigits}`;
  }
}

class CashPayment implements Payment {
  readonly amount: number;

  constructor(amount: number) {
    this.amount = amount;
  }

  label(): string {
    return "cash";
  }
}

const payments: Payment[] = [new CardPayment(20, "4321"), new CashPayment(7.5)];

let total = 0;
for (const payment of payments) {
  console.log(`$${payment.amount.toFixed(2)} by ${payment.label()}`);
  total += payment.amount;
}
console.log(`Total: $${total.toFixed(2)}`);
$20.00 by card ending 4321
$7.50 by cash
Total: $27.50
Line What happens
1–4 Payment says what every payment offers: a read-only amount and a label() method
6 CardPayment implements Payment: the checker confirms this class has both. It may also have more, such as lastDigits
20 CashPayment keeps the same promise with a different label
32 An array of the interface type holds instances of both classes
35–38 The loop knows only that each element is a Payment, so it may use amount and label(), and nothing else
36 payment.label() runs whichever class’s method the object has: the card’s on the first pass, the cash’s on the second

Line 36 is the payoff. The loop was written once, against the interface, and it works for every class that implements it. Tomorrow you could add a GiftCardPayment class and the loop would not change.

A class can implement more than one interface, separated by commas: class CardPayment implements Payment, Refundable. It must then have everything that both list.

Key idea

class C implements I asks the checker to confirm, at the class, that every instance has everything interface I lists. It adds nothing at run time. Code written against the interface type then works with every class that implements it.

Watch out

A class that does not keep its promise. A misspelled method name is the most common way:

implements-missing.ts
interface Payment {
  readonly amount: number;
  label(): string;
}

class GiftCard implements Payment {
  readonly amount: number;

  constructor(amount: number) {
    this.amount = amount;
  }

  lable(): string {
    return "gift card";
  }
}
implements-missing.ts:6:7 - error TS2420: Class 'GiftCard' incorrectly implements interface 'Payment'.
  Property 'label' is missing in type 'GiftCard' but required in type 'Payment'.

The method is spelled lable, so the class has no label. Without implements, the class itself would check clean, and the mistake would surface only where a GiftCard was used as a Payment. With it, the error points at the class, and the second line names exactly what is missing. Rename the method, then fix or delete the file.

Pause and try

Question 9 · Multiple choice

A program has interface Named { name: string; } and class Pet { name: string; constructor(name: string) { this.name = name; } }, with no implements. What does npx tsc say about const n: Named = new Pet("Rex");?

  1. It rejects it, because Pet does not say implements Named.
  2. It accepts it, because a Pet has a name string, which is all Named requires.
  3. It accepts it only if Pet also extends Named.
  4. It rejects it, because an interface cannot describe an instance of a class.
Check your reasoning

B. The checker matches shapes, exactly as on Day 10. implements is not needed for an instance to fit an interface; it only makes the checker confirm the fit at the class.

  • A is wrong: implements is a promise you choose to make, not a requirement for fitting.
  • C is wrong: a class extends another class (15.6), not an interface; and it is not needed for the fit.
  • D is wrong: an instance is an object, and an interface describes objects.

Reread 15.5 implements an Interface if you chose differently.

Question 10 · Short answer

If an instance fits an interface by shape anyway, what does writing implements Payment on a class gain you? Give one concrete situation where it helps.

Check your reasoning

Model answer: implements makes the checker compare the class with the interface where the class is written, so a missing or misspelled method is reported on the class’s own line, with the missing property named. Without it, the mistake shows up only where an instance is used as a Payment, possibly far away, or not at all if no code uses it that way yet. For example, a misspelled lable() method in GiftCard is caught as soon as the class is written, before any code tries to put a gift card in a Payment[]. It also tells a human reader what the class is for.

A complete answer must say that:

  • the check happens at the class declaration, and
  • the error then names the class and the missing property, rather than appearing wherever an instance is used.

Reread 15.5 implements an Interface if your reasoning differed.

Section 6 of 8

15.6 Inheritance with extends and super

On Day 10, interface Manager extends Employee gave the Manager description everything in Employee plus reports. Classes can do the same with real code: a manager can reuse an employee’s fields and methods instead of copying them, and change only what is different.

class Manager extends Employee makes Manager a subclass of Employee, and Employee the superclass (also called the base class). Every Manager instance has every field and method of Employee, plus whatever Manager adds. Getting fields and methods from a superclass this way is called inheritance.

Worked example: Managers are employees

employees.ts
class Employee {
  readonly name: string;
  salary: number;

  constructor(name: string, salary: number) {
    this.name = name;
    this.salary = salary;
  }

  monthly(): number {
    return this.salary / 12;
  }

  describe(): string {
    return `${this.name} earns $${this.monthly().toFixed(2)} a month`;
  }
}

class Manager extends Employee {
  reports: string[];

  constructor(name: string, salary: number, reports: string[]) {
    super(name, salary);
    this.reports = reports;
  }

  describe(): string {
    return `${super.describe()} and manages ${this.reports.length}`;
  }
}

const ana = new Employee("Ana Reyes", 52000);
const dev = new Manager("Dev Patel", 71000, ["Ana Reyes", "Ben Okafor"]);

console.log(ana.describe());
console.log(dev.describe());
console.log(dev.monthly().toFixed(2));
console.log(dev.reports);
Ana Reyes earns $4333.33 a month
Dev Patel earns $5916.67 a month and manages 2
5916.67
[ 'Ana Reyes', 'Ben Okafor' ]
Line What happens
19 Manager extends Employee: a manager has name, salary, monthly, and describe without writing them again
20 Plus one field of its own, reports
23 super(name, salary) calls Employee’s constructor, which fills in the two inherited fields. It must come before any use of this
24 Then Manager’s constructor fills in its own field
27–29 Manager writes its own describe, replacing the inherited one for managers
28 super.describe() calls Employee’s version, so the new one adds to the old text instead of repeating it
36 dev.describe() runs Manager’s describe, because dev is a Manager
37 monthly is not in Manager at all; it is inherited, and its this is dev

The word super has two jobs, and both mean “the superclass”:

Form Where What it does
super(arguments) A constructor Runs the superclass’s constructor on the new instance. Required before this is used
super.method(...) Any method Runs the superclass’s version of a method, with the same this

Writing a method in a subclass with the same name as one it inherits is called overriding the method. Its parameters and return type must fit the inherited one, so that a Manager can still be used anywhere an Employee is expected. Some code writes the word override in front of such a method, as in override describe(): string, to make the checker confirm that there really is an inherited method of that name; it is optional, and this course leaves it out.

Now vary it. A subclass that needs no new fields can leave the constructor out entirely; it then uses the superclass’s constructor as is. And overriding pays off most when one loop handles a whole mix of subclasses:

team.ts
class Employee {
  readonly name: string;

  constructor(name: string) {
    this.name = name;
  }

  role(): string {
    return "employee";
  }

  badge(): string {
    return `${this.name} (${this.role()})`;
  }
}

class Manager extends Employee {
  role(): string {
    return "manager";
  }
}

class Intern extends Employee {
  role(): string {
    return "intern";
  }
}

const team: Employee[] = [new Employee("Ana"), new Manager("Dev"), new Intern("Kai")];

for (const person of team) {
  console.log(person.badge());
}
Ana (employee)
Dev (manager)
Kai (intern)

Manager and Intern have no constructor, so new Manager("Dev") runs Employee’s. Each overrides only role. The surprising part is badge, written once in Employee: line 13 calls this.role(), and this is the actual object, so for Dev it runs Manager’s role, and for Kai Intern’s. The array on line 29 is an Employee[], and the checker accepts the subclass instances in it, because a subclass instance has everything an Employee has. Which method runs is decided by the object’s own class when the program runs, not by the array’s type.

Key idea

class Sub extends Base inherits every field and method of Base. A subclass constructor must call super(...) before using this. A method with the same name overrides the inherited one, super.method() still reaches the original, and the object’s own class decides which version runs.

Watch out

Forgetting super(...) in a subclass constructor.

missing-super.ts
class Employee {
  readonly name: string;

  constructor(name: string) {
    this.name = name;
  }
}

class Manager extends Employee {
  reports: string[];

  constructor(name: string, reports: string[]) {
    this.reports = reports;
  }
}
missing-super.ts:12:3 - error TS2377: Constructors for derived classes must contain a 'super' call.
missing-super.ts:13:5 - error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class.

A “derived class” is a subclass. Until the superclass’s constructor has run, the inherited fields are not set up, so the instance is not ready to use, and JavaScript forbids touching this. Add super(name); as the first line of the constructor, then fix or delete the file.

A related limit: a subclass’s methods cannot read the superclass’s # fields. Private means private to the class that declared it. If a subclass needs the value, give the superclass a getter.

Pause and try

Question 11 · Tracing

Predict exactly what this program shows.

predict-extends.ts
class Vehicle {
  readonly wheels: number;

  constructor(wheels: number) {
    this.wheels = wheels;
  }

  describe(): string {
    return `${this.wheels} wheels`;
  }
}

class Bike extends Vehicle {
  constructor() {
    super(2);
  }
}

class Truck extends Vehicle {
  load: number;

  constructor(load: number) {
    super(6);
    this.load = load;
  }

  describe(): string {
    return `${super.describe()}, ${this.load} t`;
  }
}

const garage: Vehicle[] = [new Bike(), new Truck(8), new Vehicle(4)];
for (const vehicle of garage) {
  console.log(vehicle.describe());
}
Check your reasoning
2 wheels
6 wheels, 8 t
4 wheels
  • new Bike() runs Bike’s constructor, which calls super(2), so wheels is 2. Bike does not override describe, so the inherited one gives 2 wheels.
  • new Truck(8) calls super(6) and then stores load. Truck overrides describe: super.describe() gives "6 wheels", and the rest adds , 8 t.
  • new Vehicle(4) is a plain vehicle: 4 wheels.

The loop calls describe on each element of a Vehicle[], and each object’s own class decides which version runs.

Reread 15.6 Inheritance with extends and super if any line differed.

Question 12 · Multiple choice

In employees.ts, what would happen if line 28 were return this.describe() + " and manages ..."; instead of using super.describe()?

  1. The same output: this.describe() and super.describe() both reach Employee’s version.
  2. this.describe() is Manager’s own describe, so the method would keep calling itself without end, and the program would crash.
  3. The checker would reject it, because this cannot be used in a subclass method.
  4. It would show the manager’s text twice and then stop.
Check your reasoning

B. this is dev, a Manager, so this.describe() runs Manager’s describe again, which calls this.describe() again, and so on until node runs out of room and stops with a RangeError. super.describe() exists exactly to reach the superclass’s version.

  • A is wrong: this.method() always starts from the object’s own class, which here is Manager.
  • C is wrong: this works in every method; after the constructor has called super, it is safe to use.
  • D is wrong: nothing stops the repeated calls, so it never finishes normally.

Reread 15.6 Inheritance with extends and super if you chose differently.

Section 7 of 8

15.7 static Members

Every field so far belonged to one instance: each cart has its own total. Some values belong to the class as a whole instead. How many tickets have been issued so far? What is the most anyone may buy? Those are not facts about one ticket, and storing a copy in each ticket would make no sense.

A static member is a field or method that belongs to the class itself, not to its instances. It is declared with the word static and reached through the class name: Ticket.issued, not first.issued. You have used one already: on Day 7, Object.keys(book) called keys, a static method of JavaScript’s built-in Object class.

Worked example: Numbered tickets

tickets.ts
class Ticket {
  static issued = 0;
  static readonly maxPerPerson = 4;

  readonly number: number;
  readonly holder: string;

  constructor(holder: string) {
    Ticket.issued += 1;
    this.number = Ticket.issued;
    this.holder = holder;
  }

  static canBuy(count: number): boolean {
    return count >= 1 && count <= Ticket.maxPerPerson;
  }
}

console.log(Ticket.issued);
const first = new Ticket("Ana");
const second = new Ticket("Ben");
console.log(`${first.holder} #${first.number}, ${second.holder} #${second.number}`);
console.log(Ticket.issued);
console.log(Ticket.canBuy(6));
0
Ana #1, Ben #2
2
false
Line What happens
2 static issued = 0: one counter for the whole class, created once, before any ticket exists
3 static readonly: a fixed setting of the class, a named constant
9 Each constructor run adds one to the shared counter, through the class name
10 and copies its current value into this ticket’s own number
14–16 A static method: called on the class, so there is no instance and no this to use. It works only from its argument and statics
19 Read before any ticket is made: 0
22 Each ticket kept the number it got: Ana #1, Ben #2
23 Two constructor runs: 2
24 6 is more than maxPerPerson: false

Now vary it. A common static method is a second way to make instances, one with a clearer name than the constructor:

temperature.ts
class Temperature {
  readonly celsius: number;

  constructor(celsius: number) {
    this.celsius = celsius;
  }

  static fromFahrenheit(fahrenheit: number): Temperature {
    return new Temperature(((fahrenheit - 32) * 5) / 9);
  }

  get fahrenheit(): number {
    return (this.celsius * 9) / 5 + 32;
  }
}

const morning = new Temperature(20);
const noon = Temperature.fromFahrenheit(86);

console.log(morning.fahrenheit);
console.log(noon.celsius);
console.log(noon.fahrenheit);
68
30
86

The constructor takes Celsius. Temperature.fromFahrenheit(86) on line 18 converts first, (86 − 32) × 5 ÷ 9 = 30, then returns new Temperature(30). It must be static: before you have a Temperature, there is no instance to call a method on. The getter fahrenheit converts back: 20 × 9 ÷ 5 + 32 is 68.

Key idea

A static field or method belongs to the class, not to any instance, and is reached through the class name: Ticket.issued, Temperature.fromFahrenheit(86). Use it for data shared by all instances, constants of the class, and functions that make instances.

Watch out

Reaching a static member through an instance.

static-on-instance.ts
class Ticket {
  static issued = 0;
  readonly holder: string;

  constructor(holder: string) {
    Ticket.issued += 1;
    this.holder = holder;
  }
}

const first = new Ticket("Ana");
console.log(first.issued);
static-on-instance.ts:12:19 - error TS2576: Property 'issued' does not exist on type 'Ticket'. Did you mean to access the static member 'Ticket.issued' instead?

An instance has only its own fields and the class’s ordinary methods; issued lives on Ticket itself. Write Ticket.issued, as the message suggests, then fix or delete the file.

Pause and try

Question 13 · Tracing

Predict exactly what this program shows.

predict-static.ts
class Visitor {
  static count = 0;
  readonly name: string;

  constructor(name: string) {
    this.name = name;
    Visitor.count += 1;
  }

  static welcome(): string {
    return `Visitors so far: ${Visitor.count}`;
  }
}

console.log(Visitor.welcome());
const ana = new Visitor("Ana");
const ben = new Visitor("Ben");
console.log(Visitor.welcome());
console.log(`${ben.name} was visitor ${Visitor.count}`);
Check your reasoning
Visitors so far: 0
Visitors so far: 2
Ben was visitor 2
  • Line 15: no visitor has been made, so the shared count is still 0.
  • Lines 16–17: each constructor run adds one to Visitor.count, which is now 2.
  • Line 18: Visitors so far: 2.
  • Line 19: ben.name is "Ben", an instance field; Visitor.count is the class’s shared count, 2.

Reread 15.7 static Members if any line differed.

Question 14 · Multiple choice

In tickets.ts, why can canBuy not use this.holder?

  1. Because holder is readonly.
  2. Because canBuy is static: it is called as Ticket.canBuy(6), on the class, so there is no ticket for this to mean.
  3. Because static methods may not have parameters.
  4. Because this can be used only in a constructor.
Check your reasoning

B. this is the object before the dot. In Ticket.canBuy(6), that is the class, not a ticket, and the class has no holder. The checker rejects this.holder inside a static method with Property 'holder' does not exist on type 'typeof Ticket': typeof Ticket is the checker’s name for the class itself.

  • A is wrong: readonly stops assignment, not reading.
  • C is wrong: canBuy has a parameter, count.
  • D is wrong: every ordinary method uses this, as 15.2 showed.

Reread 15.7 static Members if you chose differently.

Section 8 of 8

15.8 Class or Plain Objects?

You now have two complete toolkits. Days 7 to 11 built programs from plain objects described by interfaces and functions that take them; today added classes. Both can do most jobs. Choosing well makes a program shorter and easier to change, and choosing a class where it is not needed is one of the most common habits beginners pick up.

Here is a job where plain objects are simpler: points on a map, and the distance between two of them. (Math.sqrt gives a number’s square root.)

plain-point.ts
interface Point {
  x: number;
  y: number;
}

function distance(a: Point, b: Point): number {
  return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2);
}

const home: Point = { x: 0, y: 0 };
const school: Point = { x: 3, y: 4 };
const moved = { ...school, x: 0 };

console.log(distance(home, school));
console.log(distance(home, moved));
console.log(school);
5
4
{ x: 3, y: 4 }

A point is just two numbers. Any x and y are valid, so there is no rule for a class to protect. The object literals are short, console.log shows them plainly, and line 12 makes a changed copy with Day 7’s spread, leaving school untouched. Making Point a class would add a constructor and new and gain nothing.

Spread shows a real difference between the two. Copy a class instance with spread, and what comes out is a plain object with its fields only:

spread-instance.ts
class Cart {
  items: string[] = ["bread"];

  describe(): string {
    return `${this.items.length} items`;
  }
}

const cart = new Cart();
const copy = { ...cart };
console.log(copy.items);
console.log(copy.describe());
spread-instance.ts:12:18 - error TS2339: Property 'describe' does not exist on type '{ items: string[]; }'.

Methods live with the class, not in each instance, so { ...cart } copies items but not describe, and the copy is no longer a Cart. Private # fields are not copied either. At run time, line 12 would stop with TypeError: copy.describe is not a function. Plain data copies easily; instances do not. Fix or delete this file.

Now compare the jobs where today’s examples did need a class: the thermostat, the bank account in Practice, the gauge, the playlist. Each holds data that must obey a rule, and each changes over time through operations that must check that rule. That is the situation classes are for.

Choose plain objects and functions when… Choose a class when…
The data is just values, and any combination of them is valid Some combinations are invalid, and the object must protect a rule (# fields)
You mostly create, read, copy, and compare the data The data changes over time through a fixed set of operations (methods)
You will copy it with spread, or turn it into text and back You need many instances that each carry their own state, such as counters or accounts
One or two functions work on it Several kinds of thing share an interface or a base class and one loop handles them all

The closure counter from Day 10 and the class counter from 15.3 do the same job; for a single function with a remembered value, the closure is shorter, and for several operations around shared state, the class is clearer. When unsure, start with plain objects and functions; switch to a class the moment you find yourself writing “every function that changes this must first check that…”.

Key idea

Use plain objects and functions for data that is just values: they are shorter and copy cleanly with spread. Use a class when the data must stay valid while it changes, so private fields and checking methods can guard it, or when many instances or several related kinds of object share behavior.

Pause and try

Question 15 · Short answer

For each job, say whether you would write a class or use plain objects and functions, and give a one-sentence reason.

  • (a) A list of recipes, each with a name, a list of ingredients, and a cooking time, which the program sorts and prints.
  • (b) A game timer that can start, pause, and resume, and whose remaining time must never go below zero.
  • (c) RGB colors, each three numbers, and a function that mixes two of them into a new color.
Check your reasoning

Model answer:

  • (a) Plain objects with an interface: a recipe is just values, any combination is valid, and sorting and printing are jobs for Day 11’s array methods.
  • (b) A class: the timer’s state changes over time through a fixed set of operations, and a private field plus methods can guarantee the remaining time never drops below zero.
  • (c) Plain objects and a function: a color is three numbers, mixing builds a new color instead of changing one, and plain objects copy cleanly with spread.

A complete answer must tie each choice to whether there is a rule to protect while the data changes. Answering “class” for (c) is not wrong if you want a constructor to keep each number between 0 and 255, as long as you give that reason.

Reread 15.8 Class or Plain Objects? if your reasoning differed.

Wrap-up · 1 of 8

Putting it together

A small library catalog: an interface for anything that can be lent, a class that implements it with a static counter for ids, a private field, and a getter, and a subclass that overrides one method. Before you type it, make sure npx tsc is clean in your day15 folder: fix or delete any broken file from today.

library.ts
interface Lendable {
  readonly title: string;
  readonly available: boolean;
  checkOut(member: string): boolean;
  checkIn(): void;
}

class LibraryItem implements Lendable {
  static created = 0;

  readonly id: number;
  readonly title: string;
  #borrower: string | undefined = undefined;

  constructor(title: string) {
    LibraryItem.created += 1;
    this.id = LibraryItem.created;
    this.title = title;
  }

  get available(): boolean {
    return this.#borrower === undefined;
  }

  loanDays(): number {
    return 21;
  }

  checkOut(member: string): boolean {
    if (!this.available) {
      return false;
    }
    this.#borrower = member;
    return true;
  }

  checkIn(): void {
    this.#borrower = undefined;
  }

  describe(): string {
    if (this.#borrower === undefined) {
      return `#${this.id} ${this.title}: on the shelf`;
    }
    return `#${this.id} ${this.title}: with ${this.#borrower} for ${this.loanDays()} days`;
  }
}

class Dvd extends LibraryItem {
  loanDays(): number {
    return 7;
  }
}

const atlas = new LibraryItem("Atlas");
const space = new Dvd("Space");
const poems = new LibraryItem("Poems");

atlas.checkOut("Ana");
space.checkOut("Ben");
console.log(atlas.checkOut("Kai"));
poems.checkOut("Kai");
poems.checkIn();

const shelf: LibraryItem[] = [atlas, space, poems];
for (const item of shelf) {
  console.log(item.describe());
}
console.log(`${LibraryItem.created} items, ${shelf.filter((item) => item.available).length} available`);

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

false
#1 Atlas: with Ana for 21 days
#2 Space: with Ben for 7 days
#3 Poems: on the shelf
3 items, 1 available
Line What happens Idea
1–6 Lendable lists what any lendable thing offers. available is a readonly property in the interface 15.5
8 LibraryItem promises to be Lendable; the checker confirms it 15.5
9 One counter shared by every item, and by the Dvd subclass too 15.7
11–12 Set once in the constructor, then fixed 15.3
13 Who has the item, or undefined when it is on the shelf; private, so only checkOut and checkIn can change it 15.3
16–17 Each new item takes the next id 15.7
21–23 available is a getter, so it is always worked out from #borrower and can never disagree with it. It satisfies the interface’s read-only available 15.4
29–35 checkOut refuses an item that is already out, so an item can never have two borrowers 15.2, 15.3
45 this.loanDays() runs the object’s own class’s version 15.6
49–53 Dvd inherits everything, including the constructor, and overrides only loanDays 15.6
61 Atlas is already with Ana, so Kai’s request is refused: false 15.3
62–63 Poems goes out and comes back 15.2
65 A Dvd fits in a LibraryItem[] 15.6
69 created through the class name; Day 11’s filter keeps the items whose getter says they are available 15.7, Day 11

The design choice that matters most is line 13 plus lines 21 to 23. A separate available field that every method had to remember to update could drift out of step with #borrower; a getter computed from the private field cannot. That is the class keeping its own data valid.

Wrap-up · 2 of 8

Common mistakes

Today’s messages in one place; the runtime-only ones are at the bottom.

Message or symptom Usual cause Fix
TS2348: Value of type 'typeof Book' is not callable. Did you mean to include 'new'? Calling a class without new new Book(...)
TS2564: Property 'seconds' has no initializer and is not definitely assigned in the constructor. A field the constructor never sets Set it in the constructor, give it an initializer, or ?
TS2663: Cannot find name 'total'. Did you mean the instance member 'this.total'? A field used without this. inside a method this.total
TS18013: Property '#target' is not accessible outside class ... Reaching a private field from outside the class Use a method or getter the class offers
TS2540: Cannot assign to 'room' because it is a read-only property. Assigning a readonly field, or a property with only a getter Change it through a method, or drop readonly
TS6234: This expression is not callable because it is a 'get' accessor. road.count() on a getter road.count
TS2420: Class ... incorrectly implements interface ... A missing or misspelled member Add the member the second line names
TS2377: Constructors for derived classes must contain a 'super' call. A subclass constructor without super(...) Call super(...) first
TS2576: ... Did you mean to access the static member 'Ticket.issued' instead? A static member reached through an instance Use the class name
TS2339: Property 'describe' does not exist on type '{ items: string[]; }'. Calling a method on a spread copy of an instance Keep the instance, or make a new one with new
TypeError: Cannot read properties of undefined (reading 'items') A method called without its object, so this is undefined Wrap the call: () => cart.describe()
Wrap-up · 3 of 8

Vocabulary

Term Definition Example
class A blueprint for objects: their fields, how they are filled in, and their methods; also a type class Book { ... }
instance One object made from a class with new new Book("Atlas", 240)
field A value each instance stores, declared in the class pages: number;
field initializer A starting value given where a field is declared borrowed = 0;
constructor The function new runs once for each new instance, to fill in its fields constructor(title: string) { ... }
method A function declared in a class, called on an instance cart.add("milk", 1.25)
this Inside a method or constructor, the object the method was called on, or the one being built this.total += price;
private field A field whose name starts with #, reachable only by code inside the class #target = 20;
readonly field A field set once, in its initializer or the constructor, and never assigned again readonly room: string;
valid Obeying the rules the object promises at every moment A target always between 10 and 30
getter A method declared with get, read like a field without parentheses get count(): number { ... }
implements Asks the checker to confirm that a class has everything an interface lists class CashPayment implements Payment
subclass / superclass A class that extends another / the class it extends Manager / Employee
inheritance A subclass getting every field and method of its superclass dev.monthly()
super In a subclass, the superclass: super(...) runs its constructor, super.m() its method super(name, salary);
override To write a method in a subclass with the same name as an inherited one, replacing it Manager’s describe
static member A field or method that belongs to the class itself, reached through the class name Ticket.issued
Wrap-up · 4 of 8

Summary

  • A class is a blueprint and a type. Its fields list what every instance stores, its constructor fills them in when new makes an instance, and its methods work on the instance, which they reach as this: the object before the dot in the call.
  • # private fields, readonly fields, and getters let a class keep its data valid: outside code can read what the class shows, but every change goes through a method that checks it first.
  • implements makes the checker confirm, at the class, that it has everything an interface lists, so code written against the interface works with every class that implements it.
  • extends gives a subclass everything its superclass has. Its constructor must call super(...); a method of the same name overrides the inherited one, super.method() reaches the original, and the object’s own class decides which version runs.
  • Static members belong to the class, not to instances: shared counters, constants, and functions that make instances.
  • Use plain objects and functions for data that is just values; use a class when data must stay valid while it changes, or many related objects share behavior.
Wrap-up · 5 of 8

Practice

Do these in your day15 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as forget-new.ts, missing-field.ts, forgot-this.ts, private-outside.ts, readonly-assign.ts, getter-call.ts, implements-missing.ts, missing-super.ts, static-on-instance.ts, or spread-instance.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 values and run them again.

Question 16 · Short answer

Bank account. Write a BankAccount class with an owner, deposit and withdraw methods, and a read-only balance. Outside code must never be able to set the balance directly. Reject deposits and withdrawals of zero or less, and reject any withdrawal larger than the balance (an overdraft); each method should report whether it succeeded. Day 16 shows a stronger way to reject bad requests; for today, return true or false.

Check your reasoning

One possible solution:

bank-account.ts
class BankAccount {
  readonly owner: string;
  #balance = 0;

  constructor(owner: string, opening = 0) {
    this.owner = owner;
    this.deposit(opening);
  }

  get balance(): number {
    return this.#balance;
  }

  deposit(amount: number): boolean {
    if (amount <= 0) {
      return false;
    }
    this.#balance += amount;
    return true;
  }

  withdraw(amount: number): boolean {
    if (amount <= 0 || amount > this.#balance) {
      return false;
    }
    this.#balance -= amount;
    return true;
  }
}

const account = new BankAccount("Ana", 100);
console.log(account.deposit(50));
console.log(account.withdraw(500));
console.log(account.withdraw(30));
console.log(account.deposit(-20));
console.log(`${account.owner}: $${account.balance.toFixed(2)}`);

const empty = new BankAccount("Ben", -40);
console.log(empty.balance);
true
false
true
false
Ana: $120.00
0

#balance is private and balance is a getter with no setter, so account.balance = 1000000 is rejected (TS2540) and the only ways to change the money are deposit and withdraw, which check every amount. The constructor reuses deposit for the opening amount, so a negative opening balance is refused by the same check: Ben’s account starts at 0. Ana’s account: 100, +50 is 150, 500 refused, −30 is 120, −20 refused as a deposit.

Reread 15.3 Private Fields and readonly and 15.4 Getters if your result differed.

Question 17 · Short answer

Shapes. Write a Shape interface with a name, an area() method, and a perimeter() method. Write Circle and Rectangle classes that implement it. Put several of each in one array of type Shape[], print each shape’s area and perimeter to two decimal places, and print the total area.

Check your reasoning

One possible solution:

shapes.ts
interface Shape {
  readonly name: string;
  area(): number;
  perimeter(): number;
}

class Circle implements Shape {
  readonly name = "circle";
  readonly radius: number;

  constructor(radius: number) {
    this.radius = radius;
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }

  perimeter(): number {
    return 2 * Math.PI * this.radius;
  }
}

class Rectangle implements Shape {
  readonly name = "rectangle";
  readonly width: number;
  readonly height: number;

  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }

  area(): number {
    return this.width * this.height;
  }

  perimeter(): number {
    return 2 * (this.width + this.height);
  }
}

const shapes: Shape[] = [new Circle(1), new Rectangle(3, 4), new Circle(2.5)];

let totalArea = 0;
for (const shape of shapes) {
  console.log(`${shape.name}: area ${shape.area().toFixed(2)}, perimeter ${shape.perimeter().toFixed(2)}`);
  totalArea += shape.area();
}
console.log(`Total area: ${totalArea.toFixed(2)}`);
circle: area 3.14, perimeter 6.28
rectangle: area 12.00, perimeter 14.00
circle: area 19.63, perimeter 15.71
Total area: 34.78

Both classes say implements Shape, so the checker confirms each has name, area, and perimeter. The loop knows each element only as a Shape, and each object’s own area runs: π × 1² ≈ 3.14 for the first circle, 3 × 4 = 12 for the rectangle, π × 2.5² ≈ 19.63 for the second circle. Math.PI is the built-in value of π. readonly name = "circle" gives every instance the same fixed name without a constructor parameter.

Reread 15.5 implements an Interface if your result differed.

Question 18 · Short answer

Generic stack. A stack is a pile where the last item put on is the first taken off, like a stack of plates or an editor’s undo history. Write a generic class Stack<T> with push(item), pop() (remove and give back the top item), peek() (give back the top item without removing it), and a size getter. pop and peek on an empty stack should give undefined. Use it with strings and with numbers.

Check your reasoning

One possible solution:

stack.ts
class Stack<T> {
  #items: T[] = [];

  push(item: T): void {
    this.#items.push(item);
  }

  pop(): T | undefined {
    return this.#items.pop();
  }

  peek(): T | undefined {
    return this.#items.at(-1);
  }

  get size(): number {
    return this.#items.length;
  }
}

const history = new Stack<string>();
history.push("type 'Hi'");
history.push("make bold");
history.push("delete line");

console.log(history.size);
console.log(history.peek());
console.log(history.pop());
console.log(history.pop());
console.log(history.size);

const numbers = new Stack<number>();
console.log(numbers.pop());
numbers.push(42);
console.log(numbers.peek() ?? "empty");
3
delete line
delete line
make bold
1
undefined
42

The array is private, so nothing can insert into the middle of the stack or take from the bottom. Day 6’s push and pop work at the end of the array, which serves as the top of the stack, and at(-1) reads the last element without removing it. Both give undefined on an empty array, so pop and peek have the return type T | undefined. peek on line 27 and pop on line 28 both give "delete line", because peek leaves it in place. Line 33’s numbers.pop() finds the stack empty, and line 35 uses Day 9’s ?? to handle a possible undefined.

Reread 15.4 Getters if your result differed.

Wrap-up · 6 of 8

Review questions

Question 19 · Tracing

Predict exactly what this program shows.

review-scores.ts
class Scoreboard {
  #scores: number[] = [];

  add(score: number): boolean {
    if (score < 0 || score > 100) {
      return false;
    }
    this.#scores.push(score);
    return true;
  }

  get best(): number {
    let best = 0;
    for (const score of this.#scores) {
      if (score > best) {
        best = score;
      }
    }
    return best;
  }

  get average(): number {
    if (this.#scores.length === 0) {
      return 0;
    }
    let total = 0;
    for (const score of this.#scores) {
      total += score;
    }
    return total / this.#scores.length;
  }
}

const quiz = new Scoreboard();
console.log(quiz.average);
quiz.add(80);
console.log(quiz.add(120));
quiz.add(95);
quiz.add(65);
console.log(quiz.best);
console.log(quiz.average.toFixed(1));
Check your reasoning
0
false
95
80.0
  • Line 35: no scores yet, so the getter average takes its early return: 0. Without that check it would divide 0 by 0 and give NaN.
  • Line 36: 80 is accepted. Line 37: 120 is above 100, so add refuses it and returns false; it is never stored.
  • Lines 38–39: 95 and 65 are accepted, so the scores are 80, 95, and 65.
  • Line 40: best loops over them: 95.
  • Line 41: (80 + 95 + 65) ÷ 3 = 240 ÷ 3 = 80, shown with one decimal: 80.0.

Because #scores can be changed only through add, best and average can trust that every score is between 0 and 100.

Reread 15.4 Getters and 15.3 Private Fields and readonly if any line differed.

Question 20 · Debugging

npx tsc accepts this program, but node stops with TypeError: Cannot read properties of undefined (reading '#count'). Explain why, and fix it.

repeat-broken.ts
class Counter {
  #count = 0;

  increment(): void {
    this.#count += 1;
  }

  get value(): number {
    return this.#count;
  }
}

function repeat(times: number, action: () => void): void {
  for (let i = 0; i < times; i++) {
    action();
  }
}

const laps = new Counter();
repeat(3, laps.increment);
console.log(laps.value);
Check your reasoning

Line 20 passes laps.increment to repeat as a callback, without calling it. The method leaves its object behind: inside repeat, line 15 calls it as action(), with nothing before a dot, so this is undefined and this.#count on line 5 reads from undefined. The checker does not catch it, because increment fits the type () => void. Wrap the call in an arrow function so laps stays before the dot:

repeat-fixed.ts
class Counter {
  #count = 0;

  increment(): void {
    this.#count += 1;
  }

  get value(): number {
    return this.#count;
  }
}

function repeat(times: number, action: () => void): void {
  for (let i = 0; i < times; i++) {
    action();
  }
}

const laps = new Counter();
repeat(3, () => laps.increment());
console.log(laps.value);
3

Reread 15.2 Methods and this if you missed it.

Question 21 · Tracing

Predict exactly what this program shows. Alarm extends Warning, which extends Notice.

review-override.ts
class Notice {
  static sent = 0;
  readonly text: string;

  constructor(text: string) {
    this.text = text;
    Notice.sent += 1;
  }

  prefix(): string {
    return "Note";
  }

  render(): string {
    return `${this.prefix()}: ${this.text}`;
  }
}

class Warning extends Notice {
  prefix(): string {
    return "WARNING";
  }
}

class Alarm extends Warning {
  render(): string {
    return `${super.render()}!!`;
  }
}

const notices: Notice[] = [new Notice("Lunch at 12"), new Warning("Wet floor"), new Alarm("Fire drill")];
for (const notice of notices) {
  console.log(notice.render());
}
console.log(Notice.sent);
Check your reasoning
Note: Lunch at 12
WARNING: Wet floor
WARNING: Fire drill!!
3
  • The Notice uses its own render and prefix: Note: Lunch at 12.
  • The Warning inherits render from Notice, but inside it this.prefix() runs Warning’s override: WARNING: Wet floor.
  • The Alarm overrides render. super.render() runs Notice’s render (inherited by Warning), with this still the alarm, so this.prefix() is the prefix Alarm inherited from Warning: "WARNING: Fire drill", then !! is added.
  • None of the subclasses has a constructor, so all three use Notice’s, and each adds one to the static sent: 3.

Reread 15.6 Inheritance with extends and super and 15.7 static Members if any line differed.

Question 22 · Multiple choice

In bank-account.ts, a classmate replaces #balance = 0 and the getter with one field, readonly balance = 0. What happens?

  1. Nothing changes: outside code still cannot set the balance, and the methods still work.
  2. npx tsc rejects this.balance += amount inside deposit and withdraw, because a readonly field cannot be assigned even by the class’s own methods.
  3. The program checks clean, but node refuses to change the balance at run time.
  4. Outside code can now set the balance, because readonly applies only inside the class.
Check your reasoning

B. readonly means “set once, by the initializer or the constructor, then never again,” for everyone, the class included. A balance has to change, so it needs a private field (changeable inside, invisible outside) plus a getter (readable outside).

  • A is wrong: the methods would no longer be allowed to update the balance.
  • C is wrong: readonly is a checker rule, so the problem is reported by npx tsc, not by node.
  • D is wrong: it is the reverse; readonly stops assignment everywhere.

Reread 15.3 Private Fields and readonly and 15.4 Getters if you chose differently.

Question 23 · Multiple choice

Queue<T> from queue.ts is used as const line = new Queue<string>();. Which call does npx tsc reject?

  1. line.join("Cara")
  2. const first: string | undefined = line.next();
  3. line.join(42)
  4. console.log(line.size);
Check your reasoning

C. In this instance T is string, so join takes a string, and 42 is a number: TS2345.

  • A is wrong: "Cara" is a string.
  • B is wrong: next() returns T | undefined, which here is exactly string | undefined.
  • D is wrong: size is a getter, read without parentheses, and gives a number.

Reread 15.4 Getters if you chose differently.

Question 24 · Short answer

Jae writes a Point class with a constructor, x and y fields, and a distanceTo(other: Point) method, for a drawing program that stores thousands of points and often copies them with spread to make moved versions. Give Jae one reason this design will cause trouble, and suggest a simpler design.

Check your reasoning

Model answer: Spread copies only an instance’s fields, so { ...point, x: 5 } is a plain object with x and y but no distanceTo, and it is no longer a Point: calling moved.distanceTo(...) is rejected by the checker (TS2339) and would crash at run time. A point has no rule to protect, since any x and y are valid, so a class buys nothing here. Simpler: an interface Point { x: number; y: number; }, plain object literals, and a distance(a: Point, b: Point) function, as in plain-point.ts. Then every spread copy is still a Point.

A complete answer must:

  • say that spread drops methods (and private fields), so a copy is not an instance, and
  • say that a point is plain data with no rule to protect, so plain objects and a function fit better.

Reread 15.8 Class or Plain Objects? if your reasoning differed.

Wrap-up · 7 of 8

Go further

The Handbook’s classes page covers every class feature TypeScript adds, including the private, protected, and override keywords this page only mentioned, and MDN explains how classes work in JavaScript itself: TypeScript Handbook: Classes and MDN: Using classes.

Wrap-up · 8 of 8

Reflection

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

  • I can write a class with fields and a constructor, and make instances with new. Reread
  • I can write methods and say what this refers to, including why a method taken off its object crashes. Reread
  • I can protect a class’s data with # private fields and readonly fields. Reread
  • I can write a getter and use it without parentheses. Reread
  • I can make a class implement an interface and use it through the interface type. Reread
  • I can extend a class, call super, and override a method. Reread
  • I can use static fields and methods through the class name. Reread
  • I can decide whether a class or plain objects and functions fit a job, and say why. Reread