Skip to content

Generic classes

Relay needs two pieces of shared machinery that hold state: a cache for upstream lookups, and a hub that announces what happens (“job started”, “queue drained”). Both are classes from M2, and both have the same problem as the functions in the first lessons. A cache that stores unknown makes every caller cast. An event hub that takes (name: string, payload: any) lets one module emit { jobId } while another reads payload.reason.

The fix is the same too: give the class type parameters, so one definition serves many types and each use keeps its own.

Type parameters go after the class name. They are in scope in every field and method:

class Cache<K, V> {
#entries = new Map<K, { readonly value: V; readonly expiresAt: number }>()
readonly #ttlMs: number
readonly #now: () => number
constructor(ttlMs: number, now: () => number) {
this.#ttlMs = ttlMs
this.#now = now
}
set(key: K, value: V): void {
this.#entries.set(key, { value, expiresAt: this.#now() + this.#ttlMs })
}
get(key: K): V | undefined {
const entry = this.#entries.get(key)
if (entry === undefined) return undefined
if (entry.expiresAt <= this.#now()) {
this.#entries.delete(key)
return undefined
}
return entry.value
}
}
const users = new Cache<string, { name: string }>(60_000, () => 0)
users.set("u1", { name: "Ada" })
const hit = users.get("u1") // { name: string } | undefined
// @ts-expect-error: a number is not a string key
users.get(1)

The clock is passed in as now, as in earlier lessons: a test can hand the cache a fake time instead of waiting. new Cache<string, ...>(...) states the parameters. When the constructor takes arguments that mention them, TypeScript infers them, as in new Map([["a", 1]]).

A type parameter on the class is fixed when you create the instance. A parameter on a method is chosen on every call. Ask which one varies:

class Box<T> {
readonly value: T
constructor(value: T) {
this.value = value
}
// T is fixed for this box; U is chosen per call.
map<U>(f: (value: T) => U): Box<U> {
return new Box(f(this.value))
}
}
const port = new Box("8080").map(Number) // Box<number>

The cache above has one key type and one value type for its whole life, so they belong on the class. map can return a different type each time it is called, so U belongs on the method. Putting U on the class would force the caller to say up front what every future map returns.

A class parameter can have a constraint, like a function’s (lesson 1). Here is the shape of a typed event hub: one type, the event map, says which payload goes with which event name:

interface RelayEvents {
"job.started": { jobId: string; worker: string }
"job.failed": { jobId: string; reason: string }
}
declare class Hub<Events extends object> {
on<K extends keyof Events>(name: K, listener: (payload: Events[K]) => void): () => void
emit<K extends keyof Events>(name: K, payload: Events[K]): void
}
declare const hub: Hub<RelayEvents>

Your first idea for the constraint might be Events extends Record<string, unknown>: “an object with string keys”. Try it with the interface above:

type EventMap<Events extends Record<string, unknown>> = Events
interface StartedAsInterface {
"job.started": { jobId: string; worker: string }
}
type StartedAsAlias = {
"job.started": { jobId: string; worker: string }
}
type Fine = EventMap<StartedAsAlias>
// @ts-expect-error: Index signature for type 'string' is missing in type 'StartedAsInterface'
type Bad = EventMap<StartedAsInterface>

The interface version fails. Record<string, unknown> is an index signature, and an interface has none. TypeScript only treats a type as having an implicit one when it is a type alias of an object literal. Interfaces can be extended later by declaration merging, so they don’t get that shortcut. The same shape written as an alias is accepted. Whether the constraint passes then depends on how the caller declared the map, which is the wrong thing for it to care about. Events extends object accepts both, and it is all this class needs, because keyof Events does the real work.

The event hub’s two methods use the pattern from the keyof lesson. The name has type K extends keyof Events, and the payload has type Events[K]. Once K is fixed by the first argument, the second is determined by it:

interface RelayEvents {
"job.started": { jobId: string; worker: string }
"job.failed": { jobId: string; reason: string }
}
declare class Hub<Events extends object> {
on<K extends keyof Events>(name: K, listener: (payload: Events[K]) => void): () => void
emit<K extends keyof Events>(name: K, payload: Events[K]): void
}
declare const hub: Hub<RelayEvents>
hub.on("job.started", (p) => p.worker) // p: { jobId: string; worker: string }
hub.emit("job.failed", { jobId: "j1", reason: "timeout" })
// @ts-expect-error: a job.failed payload needs a reason
hub.emit("job.failed", { jobId: "j1" })
// @ts-expect-error: unknown event name
hub.emit("job.exploded", { jobId: "j1" })

The listener’s parameter p has no annotation, and TypeScript fills it in from the name you passed. This is the bug the type prevents: emitting { jobId } for job.failed and having a listener crash on payload.reason.toUpperCase() in production.

on returns a function that removes the listener. It’s a useful shape for anything you register: the caller holds one value that undoes it, and nobody needs the listener’s identity again.

class Registry<T> {
#items = new Set<T>()
add(item: T): () => void {
this.#items.add(item)
return () => {
this.#items.delete(item)
}
}
get size(): number {
return this.#items.size
}
}
const registry = new Registry<string>()
const remove = registry.add("a")
remove()
registry.size // 0

The returned function closes over item, so it removes exactly what was added.

Static members can’t use the class’s type parameters

Section titled “Static members can’t use the class’s type parameters”

Type parameters belong to instances: Cache<string, User> and Cache<number, Job> are different types. A static member belongs to the class itself, shared by all of them, so there is no K for it to use:

class Cache<K, V> {
// @ts-expect-error: Static members cannot reference class type parameters
static from(key: K, value: V): Cache<K, V> {
return new Cache()
}
}

Give the static method its own parameters instead. They are ordinary function type parameters:

class Cache<K, V> {
#entries = new Map<K, V>()
static of<K2, V2>(key: K2, value: V2): Cache<K2, V2> {
const cache = new Cache<K2, V2>()
cache.#entries.set(key, value)
return cache
}
get size(): number {
return this.#entries.size
}
}
Cache.of("u1", { name: "Ada" }).size // Cache<string, { name: string }>

TypedEmitter<Events> is Relay’s notification hub. The starter stores listeners correctly enough, but takes any name and any payload, has no once, returns nothing from on or emit, and stops calling listeners when one throws. Type it from the event map, add the missing pieces, and read the Rules in the header for what happens when a listener throws.

  • Type parameters on a class are fixed per instance and visible in every member. A method can have its own for things that vary per call.
  • Constrain an event map with extends object. Record<string, unknown> rejects interfaces, which have no index signature.
  • K extends keyof Events for the name and Events[K] for the payload keep the two arguments consistent, and give listeners a precise parameter type.
  • Return an unsubscribe function from anything you register.
  • static members can’t use the class’s type parameters. Give them their own.