Skip to content

Classes

transition takes a job and an event and returns a result. Nothing in it remembers anything. But Relay has to keep its jobs somewhere between webhooks: a map from id to job, with rules such as “no two jobs share an id” and “an event for an unknown job is rejected”. If any module can reach into that map, any module can break those rules.

A class bundles state with the only code allowed to change it. This lesson covers the parts of classes you’ll use, and when a plain object and some functions is still the better choice.

class Counter {
count: number
constructor(start: number) {
this.count = start
}
increment(): number {
this.count += 1
return this.count
}
}
const c = new Counter(0)
c.increment() // 1

Declare fields in the class body and assign them in the constructor. Don’t use constructor parameter properties (constructor(readonly x: number)): they need the compiler to generate code, so they’re non-erasable syntax. The erasableSyntaxOnly flag from enums reports them.

readonly fields can be set in the constructor and nowhere else:

class Job {
readonly id: string
constructor(id: string) {
this.id = id
}
rename(id: string) {
// @ts-expect-error: cannot assign to a read-only property
this.id = id
}
}

TypeScript’s private keyword is a compile-time check. At runtime the field is an ordinary property. #name is JavaScript’s own private field, enforced by the runtime:

class Store {
private tsPrivate = 1
#hardPrivate = 2
peek(): number {
return this.tsPrivate + this.#hardPrivate
}
}
const store = new Store()
// @ts-expect-error: tsPrivate is private
store.tsPrivate
Object.keys(store) // ["tsPrivate"], and #hardPrivate is not there
JSON.stringify(store) // '{"tsPrivate":1}'

tsPrivate is hidden from the compiler only. It shows up in Object.keys, in JSON.stringify and in logs, and plain JavaScript can read it. A Relay store that serializes itself into a response would leak every job through a private field. Use # when the state must really stay inside.

A getter reads like a property and runs like a method:

class Queue {
#items: string[] = []
get size(): number {
return this.#items.length
}
push(item: string): void {
this.#items.push(item)
}
static of(...items: string[]): Queue {
const queue = new Queue()
for (const item of items) queue.push(item)
return queue
}
}
Queue.of("a", "b").size // 2

static members belong to the class, not to instances. A static factory like Queue.of is a named way to construct, useful when “new and empty” isn’t the only useful starting point.

An abstract class is a base with some behavior filled in and some left to subclasses. Relay needs the current time but tests need a fixed one:

abstract class Clock {
abstract now(): number
elapsed(since: number): number {
return this.now() - since
}
}
class SystemClock extends Clock {
override now(): number {
return Date.now()
}
}
class FixedClock extends Clock {
readonly at: number
constructor(at: number) {
super()
this.at = at
}
override now(): number {
return this.at
}
}
new FixedClock(100).elapsed(40) // 60

new Clock() is an error because the class is abstract. override marks a method that replaces a parent’s. With noImplicitOverride (from M1’s tooling lesson) it is required, so a renamed parent method can’t silently leave the child’s copy unused.

An interface describes a shape and has no code. Use an abstract class when subclasses should share real behavior (elapsed). Use an interface when they only share a contract. A class can satisfy an interface with implements; type vs interface covers that.

instanceof narrows to a class, as it did for Error in M1:

abstract class Clock {
abstract now(): number
}
class FixedClock extends Clock {
at = 0
override now(): number {
return this.at
}
}
function describe(clock: Clock): string {
if (clock instanceof FixedClock) return `fixed at ${clock.at}` // FixedClock
return `now ${clock.now()}`
}

Most of the last lesson didn’t need a class. start, fail and transition take values and return values. A plain object type plus functions is easier to test, copy and send over the wire, and it has no this to get wrong.

A class earns its place when it owns mutable state with invariants: the map of jobs, a rate limiter’s counters, a connection. The invariants live in one place, and # keeps everyone else out.

JobStore owns Relay’s jobs. The starter’s map is private (visible at runtime), size is a method, enqueue accepts duplicates, apply passes a possibly-missing job to transition, and there is no counts(). transition is given and correct: it’s the previous lesson’s solution.

  • Declare fields, assign in the constructor, and avoid parameter properties: they aren’t erasable.
  • private is compile-time only. #private is enforced at runtime and stays out of Object.keys and JSON.stringify.
  • Getters read like properties. static factories give a class named constructors.
  • abstract classes share behavior, interfaces share contracts. Mark replacements with override.
  • Use a class for owned mutable state with invariants. Use plain objects and functions otherwise.