Skip to content

Typeclass patterns

Relay’s queue view must list jobs by priority, then by how long they have waited, then by id so the order is stable. The dashboard must merge stats that each worker reports: add the counts, keep the slowest time. Both were written as loops with a hand-made comparator and a hand-made merge, and both were copied three times. One copy compared queuedAt the wrong way round.

Each of these is one small idea: “how do I compare two of these” or “how do I combine two of these”. This lesson writes the ideas down as interfaces, once, and builds the rest from them.

In Haskell a typeclass is a language feature. In TypeScript it is an interface, an object that implements it, and a function that takes the object as an argument:

interface Eq<A> {
readonly equals: (a: A, b: A) => boolean
}
interface Ord<A> extends Eq<A> {
readonly compare: (a: A, b: A) => -1 | 0 | 1
}
const ordNumber: Ord<number> = {
equals: (a, b) => a === b,
compare: (a, b) => (a < b ? -1 : a > b ? 1 : 0),
}
function sortBy<A>(ord: Ord<A>) {
return (xs: readonly A[]): A[] => xs.toSorted(ord.compare)
}
sortBy(ordNumber)([3, 1, 2]) // [1, 2, 3]

The object is passed explicitly. Nothing is looked up behind your back, so you can see which ordering a call uses and have two orderings of the same type side by side: priority first, or age first. A method on the class would allow only one.

The value of an instance is that new ones come from old ones. contramap turns an Ord<A> into an Ord<B> when you know how to get an A out of a B:

interface Ord<A> {
readonly equals: (a: A, b: A) => boolean
readonly compare: (a: A, b: A) => -1 | 0 | 1
}
declare const ordNumber: Ord<number>
interface QueuedJob {
readonly id: string
readonly priority: number
readonly queuedAt: number
}
const contramap = <A, B>(ord: Ord<A>, f: (b: B) => A): Ord<B> => ({
equals: (x, y) => ord.equals(f(x), f(y)),
compare: (x, y) => ord.compare(f(x), f(y)),
})
const reverse = <A>(ord: Ord<A>): Ord<A> => ({
equals: ord.equals,
compare: (x, y) => ord.compare(y, x),
})
const byQueuedAt = contramap(ordNumber, (j: QueuedJob) => j.queuedAt)
const byPriorityDesc = reverse(contramap(ordNumber, (j: QueuedJob) => j.priority))

The name sounds odd, but the direction is the point. map pushes a function over the output of something. contramap pushes it over the input: to compare jobs by queuedAt, first turn each job into its queuedAt. The comparison code is written once, in ordNumber, and cannot be wrong per field.

A Semigroup says how to combine two values of one type. A Monoid is a Semigroup with a neutral value, empty, that changes nothing when combined:

interface Semigroup<A> {
readonly concat: (a: A, b: A) => A
}
interface Monoid<A> extends Semigroup<A> {
readonly empty: A
}
const sumMonoid: Monoid<number> = { empty: 0, concat: (a, b) => a + b }
const maxMonoid: Monoid<number> = { empty: -Infinity, concat: (a, b) => Math.max(a, b) }
const concatAll =
<A>(m: Monoid<A>) =>
(xs: readonly A[]): A =>
xs.reduce(m.concat, m.empty)
concatAll(sumMonoid)([1, 2, 3]) // 6
concatAll(maxMonoid)([]) // -Infinity, not a crash

Two laws make this safe to use. concat is associative: concat(concat(a, b), c) equals concat(a, concat(b, c)), so it does not matter how the list is split, which is what lets you merge stats from workers in any grouping. And concat(empty, a) equals a. That second law is what makes an empty list well defined. Array.prototype.reduce without a starting value throws on []. concatAll cannot.

Neither law is checked by the compiler. The tests in the exercise check them for the instances you write. Subtraction is not associative, so { concat: (a, b) => a - b } type-checks and is not a Semigroup.

Instances combine into bigger instances. Relay’s per-worker stats are a record, and a Monoid for the whole record uses a Monoid for each field:

interface Semigroup<A> {
readonly concat: (a: A, b: A) => A
}
interface Monoid<A> extends Semigroup<A> {
readonly empty: A
}
declare const sumMonoid: Monoid<number>
declare const maxMonoid: Monoid<number>
interface SourceStats {
readonly received: number
readonly failed: number
readonly slowestMs: number
}
const statsMonoid: Monoid<SourceStats> = {
empty: { received: sumMonoid.empty, failed: sumMonoid.empty, slowestMs: maxMonoid.empty },
concat: (a, b) => ({
received: sumMonoid.concat(a.received, b.received),
failed: sumMonoid.concat(a.failed, b.failed),
slowestMs: maxMonoid.concat(a.slowestMs, b.slowestMs),
}),
}
const recordMonoid = <A>(m: Semigroup<A>): Monoid<Readonly<Record<string, A>>> => ({
empty: {},
concat: (left, right) => {
const out: Record<string, A> = { ...left }
for (const [key, value] of Object.entries(right)) {
const current = out[key]
out[key] = current === undefined ? value : m.concat(current, value)
}
return out
},
})
const perSource = recordMonoid(statsMonoid)

perSource merges two { github: ..., stripe: ... } reports key by key. A worker’s report, a minute’s report and a day’s report all use the same instance. The out object is local and discarded, so the function is still pure (lesson 1).

Ordering composes as well. Ord<A> is itself a Monoid: combine two orders by “use the first, and only if it says equal, use the second”. Its neutral element says equal for everything:

interface Ord<A> {
readonly equals: (a: A, b: A) => boolean
readonly compare: (a: A, b: A) => -1 | 0 | 1
}
interface Monoid<A> {
readonly empty: A
readonly concat: (a: A, b: A) => A
}
const ordMonoid = <A>(): Monoid<Ord<A>> => ({
empty: { equals: () => true, compare: () => 0 },
concat: (x, y) => ({
equals: (a, b) => x.equals(a, b) && y.equals(a, b),
compare: (a, b) => {
const first = x.compare(a, b)
return first !== 0 ? first : y.compare(a, b)
},
}),
})

With that, the queue order is a list: concatAll(ordMonoid<QueuedJob>())([byPriorityDesc, byQueuedAt, byId]). Adding a tie-breaker is adding a line, not editing a comparator.

Everything so far abstracts over a type A. Sometimes you want to abstract over a container: “anything with a map”, whether it is an array, an Option or a Result. That needs a type parameter that is itself a type constructor, F<_>, and TypeScript does not have those.

The usual workaround is a registry. An interface maps a string name to the container applied to A, and a helper type looks the container up by name:

type Option<A> = { readonly _tag: "Some"; readonly value: A } | { readonly _tag: "None" }
interface KindRegistry<A> {
Array: readonly A[]
Option: Option<A>
}
type Name = keyof KindRegistry<unknown>
type Kind<F extends Name, A> = KindRegistry<A>[F]
interface Functor<F extends Name> {
readonly map: <A, B>(fa: Kind<F, A>, f: (a: A) => B) => Kind<F, B>
}
const functorArray: Functor<"Array"> = { map: (fa, f) => fa.map(f) }
const double =
<F extends Name>(F: Functor<F>) =>
(fa: Kind<F, number>): Kind<F, number> =>
F.map(fa, (n) => n * 2)
double(functorArray)([1, 2, 3]) // readonly number[]

A “functor” is just this: a container with a map that keeps its shape. Interface merging, from M4 lesson 10, lets another module add a line such as Result: Result<A, unknown> to KindRegistry without editing the original, which is why this encoding is open-ended.

The starter gives the four interfaces and a few instances. You write the combinators: contramap, reverse, ordMonoid, sortBy, concatAll, the two number monoids, and the instances Relay needs: ordJob, statsMonoid and recordMonoid. The tests check tie-breaking, empty lists, neutral elements, and that no input array or record is changed.

  • A typeclass here is an interface, an object that implements it, and a function that takes the object as a parameter.
  • contramap derives an Ord<B> from an Ord<A> and a projection B -> A. The comparison logic lives in one place.
  • A Semigroup combines two values. A Monoid adds a neutral empty, so folding an empty list is defined. The laws (associativity, identity) are your job to test.
  • Instances compose: stats from fields, records from values, orderings from orderings.
  • Higher-kinded types are encoded with a registry interface. Use it for libraries, not for application code.