Dependencies as types
Until now Relay was a library of functions. From this module it is a service that runs for days. Its
worker loop needs a queue, a store, a clock, a logger and an HTTP notifier. The first version of
processJob imported a logger module and called fetch directly. It worked until a test sent a
real notification to the team channel, and until nobody could say what processJob actually needed.
The fix is not a framework. It is a type. If the dependencies of a function are written in its signature, the compiler can check that every caller supplies them, and a test can supply fakes.
A port is a one-field interface
Section titled “A port is a one-field interface”A port describes one capability. Its single field is named after the capability, so ports can be
joined with & without their members clashing.
interface Job { readonly id: string readonly kind: string}interface LoggerPort { readonly logger: { info(msg: string): void; error(msg: string): void }}interface ClockPort { readonly clock: { now(): number }}
function describe(deps: LoggerPort & ClockPort, job: Job): void { deps.logger.info(`${job.kind} ${job.id} at ${deps.clock.now()}`)}describe asks for exactly the ports it uses. It does not know where the logger writes or what the
clock is. Passing a bigger object is fine, because structural typing only
checks that the fields are there.
Requirements are an intersection
Section titled “Requirements are an intersection”A function that calls other functions needs everything they need. Write that as the intersection of their ports:
interface Job { readonly id: string readonly kind: string}interface LoggerPort { readonly logger: { info(msg: string): void }}interface NotifyPort { readonly notify: { send(text: string): Promise<void> }}interface ClockPort { readonly clock: { now(): number }}
declare function stamp(deps: ClockPort, job: Job): stringdeclare function announce(deps: NotifyPort & LoggerPort, text: string): Promise<void>
async function processJob(deps: ClockPort & NotifyPort & LoggerPort, job: Job): Promise<void> { await announce(deps, stamp(deps, job))}Pass deps straight through. The whole object satisfies each callee’s smaller requirement, so no
pick-and-copy code is needed. If announce later also needs a QueuePort, processJob stops
compiling until you add it to its own signature. The requirement flows up the call chain, checked at
every step.
Derive requirements from callees
Section titled “Derive requirements from callees”Writing the intersection by hand is easy to get stale. You can ask the compiler for it instead.
Parameters<typeof f>[0] is the type of the first parameter (conditional types
are what make Parameters work):
interface LoggerPort { readonly logger: { info(msg: string): void }}interface NotifyPort { readonly notify: { send(text: string): Promise<void> }}
declare function processJob(deps: LoggerPort & NotifyPort, id: string): Promise<void>
type JobDeps = Parameters<typeof processJob>[0]
declare function makeJobDeps(): JobDepsmakeJobDeps is tied to processJob. Add a port to processJob and makeJobDeps stops compiling
until it provides it. Use this for the composition root, not inside business functions: there, the
explicit intersection is better documentation.
The composition root builds the real object
Section titled “The composition root builds the real object”Somewhere near main you build one object with the real implementations and pass it down. This is
the only place that knows which logger, clock and HTTP client are real:
interface LoggerPort { readonly logger: { info(msg: string): void }}interface ClockPort { readonly clock: { now(): number }}interface NotifyPort { readonly notify: { send(text: string): Promise<void> }}
declare function processJob(deps: LoggerPort & ClockPort & NotifyPort, id: string): Promise<void>
const deps: LoggerPort & ClockPort & NotifyPort = { logger: { info: (msg) => console.log(msg) }, clock: { now: () => Date.now() }, notify: { async send(text) { await fetch("https://notifier.example.com/send", { method: "POST", body: text }) }, },}
await processJob(deps, "j1")Remove the notify field and the declaration of deps is the error, in one place, at build time. The
same mistake with a global would be a TypeError in production at 3 a.m. when the first job fails.
Tests pass fakes, one per port
Section titled “Tests pass fakes, one per port”Because describe asks for LoggerPort & ClockPort and nothing else, the test builds exactly that:
interface LoggerPort { readonly logger: { info(msg: string): void }}interface ClockPort { readonly clock: { now(): number }}
declare function describe(deps: LoggerPort & ClockPort, id: string): void
const lines: string[] = []describe({ logger: { info: (m) => void lines.push(m) }, clock: { now: () => 1000 } }, "j1")
// @ts-expect-error: the clock port is missingdescribe({ logger: { info: () => {} } }, "j1")No mocking library and no patching of modules. The fake is a plain object, and the compiler tells you when a function starts needing something your fake does not have.
When not to use it
Section titled “When not to use it”A function that only transforms its arguments needs no ports. Do not pass deps to parseJob just
for uniformity. Also keep ports small: a deps.everything object with 20 fields gives every function
access to everything and brings back the hidden-requirement problem, just with more typing.
Exercise
Section titled “Exercise”Wire processJob and makeDeps. processJob must ask for a logger, a notifier and a clock. The
starter asks only for a logger and never notifies, so the tests (and the @ts-expect-error checks)
fail. makeDeps turns three plain functions from the environment into the one deps object.
- A port is a one-field interface per capability:
LoggerPort,ClockPort,NotifyPort. - A function takes
deps: A & Bfor exactly the ports it uses. Requirements are the intersection of what its callees need. Parameters<typeof f>[0]derives the requirements offso the composition root cannot fall behind.- One composition root builds the real object. A missing port is a compile error there.
- Tests pass small fakes per port. No globals, no mocking library, no container.
Further reading
Section titled “Further reading”- Classes:
readonlyfields andimplements.