Capstone: effects as values
The module so far moved Relay’s decisions into pure functions: validate, route, plan a retry. What
is left in the imperative shell is the part that does things: send the notification, write to the
store, read the clock. In M5 those are ports on a deps object, and the function
that uses them runs as soon as you call it.
This lesson takes the next step. A job handler becomes a value that describes what it will do, what it needs, and how it can fail. Nothing happens until you run it. The compiler tracks the result, the errors and the requirements, so a missing service or an unhandled error is a type error at the call site.
From doing to describing
Section titled “From doing to describing”A function that sends a notification does it when called. A function that returns a description of sending one does not:
interface Notifier { send(text: string): Promise<void>}
// Eager: calling it sends.async function notifyNow(n: Notifier, text: string): Promise<void> { await n.send(text)}
// A value: calling it builds a plan. Nothing is sent yet.const notifyLater = (text: string) => (n: Notifier) => n.send(text)
const plan = notifyLater("deploy finished")declare const notifier: Notifierawait plan(notifier) // the only line that sendsawait plan(notifier) // and it can be done againA plan is a normal value. It can be stored in an array, returned from a function, wrapped with a
retry, or run twice. Program<A, E, R> is this idea with the three things we care about written
in the type.
The three parameters
Section titled “The three parameters”type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}
const succeed = <A>(value: A): Program<A> => ({ run: async () => ({ ok: true, value }) })const fail = <E>(error: E): Program<never, E> => ({ run: async () => ({ ok: false, error }) })
const answer: Program<number> = succeed(42)const boom: Program<never, "boom"> = fail("boom")Ais what the program produces when it works.Eis how it can fail.nevermeans it cannot, and the defaultneveris whysucceedneeds no annotation.Ris what it needs to run: the environment.unknownmeans nothing, sosucceedcan run anywhere.
R is written in because it is a parameter of run: contravariant, as in M5’s variance
lesson. A program that needs less can be used where more is available.
The program itself is an object holding one function, so building it does no work.
Two choices make the type small. Failures are values (Result, from M3), so
run never rejects for an expected error. And the whole thing is just data and closures, which
is why it fits on a page. This is a teaching model, not a production runtime: it has no
cancellation, no concurrency and no resource safety.
Wrapping the outside world
Section titled “Wrapping the outside world”sync wraps a function that cannot fail. promise wraps an async function that might reject, and
makes you say which typed error a rejection becomes:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}
const promise = <A, E>(thunk: () => Promise<A>, onError: (cause: unknown) => E): Program<A, E> => ({ run: async () => { try { return { ok: true, value: await thunk() } } catch (cause) { return { ok: false, error: onError(cause) } } },})
class NotifyFailed { readonly _tag = "NotifyFailed" constructor(readonly cause: unknown) {}}
declare const send: (text: string) => Promise<void>const notify: Program<void, NotifyFailed> = promise( () => send("deploy finished"), (cause) => new NotifyFailed(cause),)The thunk is lesson 10 again: the call to send is delayed until the program runs.
The catch is the one place that turns a thrown value into a typed one, the same edge rule as in
M5 lesson 2, now written once for every program.
Combining programs
Section titled “Combining programs”map changes the result. flatMap runs a second program that depends on the first one’s value.
The type of the combination is the join of both: errors are a union, requirements are an
intersection:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}
const flatMap = <A, B, E, R, E2, R2>( p: Program<A, E, R>, f: (a: A) => Program<B, E2, R2>,): Program<B, E | E2, R & R2> => ({ run: async (env) => { const r = await p.run(env) return r.ok ? f(r.value).run(env) : r },})
declare const readClock: Program<number, never, { readonly clock: { now(): number } }>declare const save: (at: number) => Program<void, "StoreDown", { readonly store: { save(at: number): void } }>
const stamped = flatMap(readClock, save)// Program<void, "StoreDown", { clock } & { store }>Why & for requirements? The first step needs a clock, the second needs a store. The whole thing
needs an object that has both, and that is what an intersection means. The same trick built
WorkerDeps in M5, except that now the compiler builds it for you.
flatMap chains nest quickly. Lesson 6 fixed that for Result with generators.
The same trick works here, with one extra step.
Do-notation for programs
Section titled “Do-notation for programs”A generator can yield* a Program if the program is iterable. Every program yields itself, and the
gen runner runs it: on success it sends the value back into the generator, on failure it stops:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>> [Symbol.iterator](): Generator<Program<unknown, E, R>, A, unknown>}
function make<A, E, R>(run: (env: R) => Promise<Result<A, E>>): Program<A, E, R> { const self: Program<A, E, R> = { run, *[Symbol.iterator]() { // The one cast: gen sends the value back in, and the type system cannot see that. return (yield self) as A }, } return self}
type ErrorOf<Y> = Y extends Program<unknown, infer E, never> ? E : never// Not distributive on purpose: several contravariant candidates for R are combined with &.type EnvOf<Y> = [Y] extends [Program<unknown, unknown, infer R>] ? R : never
function gen<Y extends Program<unknown, unknown, never>, A>( body: () => Generator<Y, A, unknown>,): Program<A, ErrorOf<Y>, EnvOf<Y>>function gen(body: () => Generator<Program<unknown, unknown, object>, unknown, unknown>) { return make(async (env: object) => { const it = body() let step = it.next() while (!step.done) { const r = await step.value.run(env) if (!r.ok) { it.return(undefined) return r } step = it.next(r.value) } return { ok: true as const, value: step.value } })}
declare const a: Program<number, "NotFound", { readonly db: string }>declare const b: Program<string, "Timeout", { readonly clock: number }>
const both = gen(function* () { const n = yield* a const s = yield* b return `${s}${n}`})const check: Program<string, "NotFound" | "Timeout", { readonly db: string } & { readonly clock: number }> = bothY is the union of everything the body yields. ErrorOf reads the error type out of each yielded
program and unions them. EnvOf does the same for requirements, but intersects. You wrote none of it
in both. It was inferred from the yield* lines, the same way lesson 6 inferred a Result’s
error union.
Two casts exist, both in the engine and both explained. One is as A in make, because the
generator’s next carries unknown. The other is the loose second signature of gen: the public
overload is exact, and the implementation behind it uses object for the environment. Nothing in
user code needs a cast.
Errors: catchTag
Section titled “Errors: catchTag”E is a union of tagged classes (M5 lesson 2). catchTag handles one of them and
removes it from the union:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}
type Tagged = { readonly _tag: string }type TagOf<E> = E extends Tagged ? E["_tag"] : never
declare function catchTag<A, E, R, T extends TagOf<E>, B, E2, R2>( p: Program<A, E, R>, tag: T, handler: (error: Extract<E, { readonly _tag: T }>) => Program<B, E2, R2>,): Program<A | B, Exclude<E, { readonly _tag: T }> | E2, R & R2>
interface InvalidPayload { readonly _tag: "InvalidPayload"}interface NotifyFailed { readonly _tag: "NotifyFailed"}declare const handle: Program<"done", InvalidPayload | NotifyFailed>declare const skipped: Program<"skipped">
const recovered = catchTag(handle, "InvalidPayload", () => skipped)// Program<"done" | "skipped", NotifyFailed, unknown>
// @ts-expect-error: "Nope" is not an error tag this program can fail withcatchTag(handle, "Nope", () => skipped)T extends TagOf<E> means you can only name a tag that can really happen, and a typo is a compile
error. Extract gives the handler the exact error class. Exclude removes it from the result, so
after you handle every tag, E is never and the type says the program cannot fail.
Requirements: service, provide, run
Section titled “Requirements: service, provide, run”service is a program that reads one entry from the environment. Its R is that single key, so
using it in a gen adds the key to the requirements:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}
declare const service: <S>() => <K extends string>(key: K) => Program<S, never, { readonly [P in K]: S }>declare function provide<A, E, R, P extends Partial<R>>( p: Program<A, E, R>, services: P,): Program<A, E, Omit<R, keyof P>>declare const run: <A, E, R>(p: Program<A, E, R>, env: NoInfer<R>) => Promise<Result<A, E>>
interface Clock { now(): number}interface Store { save(text: string): Promise<void>}declare const program: Program<void, never, { readonly clock: Clock } & { readonly store: Store }>declare const clock: Clockdeclare const store: Store
const needsStore = provide(program, { clock })// Program<void, never, Omit<{ clock } & { store }, "clock">>
// @ts-expect-error: the store has not been providedrun(needsStore, {})
await run(needsStore, { store })provide supplies some services now and removes them from R. run accepts a program only with an
environment that covers what is left. NoInfer stops the environment you pass from widening R
(see M4 lesson 9): the program decides what it needs, the caller must meet it.
This is the port idea from M5, moved from convention to type. There, deps: LoggerPort & ClockPort was a parameter you had to remember to thread through every call. Here, the
requirement is inferred from the body and attached to the program. You cannot forget to
pass a service, and you cannot pass a program around without its needs travelling with it.
Relay’s job handling as a Program
Section titled “Relay’s job handling as a Program”Relay’s handler parses the payload, notifies, then saves the outcome. It reads three services and
has three ways to fail. Write it as one gen block:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>> [Symbol.iterator](): Generator<Program<unknown, E, R>, A, unknown>}type ErrorOf<Y> = Y extends Program<unknown, infer E, never> ? E : nevertype EnvOf<Y> = [Y] extends [Program<unknown, unknown, infer R>] ? R : neverdeclare function gen<Y extends Program<unknown, unknown, never>, A>( body: () => Generator<Y, A, unknown>,): Program<A, ErrorOf<Y>, EnvOf<Y>>declare function promise<A, E>(thunk: () => Promise<A>, onError: (cause: unknown) => E): Program<A, E>declare const service: <S>() => <K extends string>(key: K) => Program<S, never, { readonly [P in K]: S }>declare const textOf: (job: Job) => Program<string, InvalidPayload>
interface Job { readonly id: string}interface Clock { now(): number}interface Notifier { send(text: string): Promise<void>}interface Store { save(jobId: string, outcome: string, at: number): Promise<void>}class InvalidPayload { readonly _tag = "InvalidPayload"}class NotifyFailed { readonly _tag = "NotifyFailed" constructor(readonly cause: unknown) {}}class StoreUnavailable { readonly _tag = "StoreUnavailable" constructor(readonly cause: unknown) {}}
const clock = service<Clock>()("clock")const notifier = service<Notifier>()("notifier")const store = service<Store>()("store")
const handleJob = (job: Job) => gen(function* () { const text = yield* textOf(job) const notify = yield* notifier yield* promise( () => notify.send(text), (cause) => new NotifyFailed(cause), ) const at = (yield* clock).now() const db = yield* store yield* promise( () => db.save(job.id, "done", at), (cause) => new StoreUnavailable(cause), ) return "done" as const })Hover over handleJob(job) in your editor. Its type is
Program< "done", InvalidPayload | NotifyFailed | StoreUnavailable, { readonly notifier: Notifier } & { readonly clock: Clock } & { readonly store: Store }>and you typed none of it. Compare with M5’s handleJob: it returned a Promise<Result<...>> and took
deps. This one returns a plan whose signature lists what it needs and how it fails, and
that list is checked, not documented.
The policy goes on top, with catchTag. An invalid payload will never get better, so record it and move
on. A failed notification should be retried. A store failure is not ours to hide:
declare const handleJob: (job: Job) => Program<"done", InvalidPayload | NotifyFailed | StoreUnavailable, Needs>declare const saveInvalid: (job: Job) => Program<"invalid", StoreUnavailable, Needs>declare function succeed<A>(a: A): Program<A>declare function catchTag<A, E, R, T extends TagOf<E>, B, E2, R2>( p: Program<A, E, R>, tag: T, handler: (error: Extract<E, { readonly _tag: T }>) => Program<B, E2, R2>,): Program<A | B, Exclude<E, { readonly _tag: T }> | E2, R & R2>
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}type Tagged = { readonly _tag: string }type TagOf<E> = E extends Tagged ? E["_tag"] : neverinterface Job { readonly id: string}interface Needs { readonly notifier: unknown}interface InvalidPayload { readonly _tag: "InvalidPayload"}interface NotifyFailed { readonly _tag: "NotifyFailed"}interface StoreUnavailable { readonly _tag: "StoreUnavailable"}
const handleJobSafely = (job: Job) => catchTag( catchTag(handleJob(job), "InvalidPayload", () => saveInvalid(job)), "NotifyFailed", () => succeed("retry" as const), )// Program<"done" | "invalid" | "retry", StoreUnavailable, Needs>Testing without mocks
Section titled “Testing without mocks”A test builds a plain object with three fakes and runs the program. The fakes write to one log, and the log is the assertion:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}declare const run: <A, E, R>(p: Program<A, E, R>, env: NoInfer<R>) => Promise<Result<A, E>>interface Job { readonly id: string}interface Env { readonly clock: { now(): number } readonly notifier: { send(text: string): Promise<void> } readonly store: { save(jobId: string, outcome: string, at: number): Promise<void> }}declare const handleJobSafely: (job: Job) => Program<"done" | "invalid" | "retry", unknown, Env>
const log: string[] = []const env: Env = { clock: { now: () => 1000 }, notifier: { send: async (text) => void log.push(`send ${text}`) }, store: { save: async (id, outcome, at) => void log.push(`save ${id} ${outcome} ${at}`) },}
const result = await run(handleJobSafely({ id: "a" }), env)// result: { ok: true, value: "done" }, log: ["send hello", "save a done 1000"]There is no mocking library and no patched module. A fake is a few lines of the interface it stands
in for, and a test that needs a failing notifier passes one that rejects. The test file also holds the
type-level checks: Expect<Equal<...>> on the inferred E and R, and @ts-expect-error on a run that
leaves a service out. Those checks are the reason to build this: they fail if inference breaks.
Exercise
Section titled “Exercise”The starter gives the types, the constructors, gen and run. You write flatMap, service,
provide, catchTag, and then Relay’s handleJob and handleJobSafely on top of them. The rules at the
top list the exact error messages and the order of effects. The tests run your programs with fakes and check
the inferred E and R types, including the call that must not compile.
Run it locally
Section titled “Run it locally”In the Relay project, put the model in src/program.ts. It is about a hundred lines and has no
dependencies:
export type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }export const ok = <A>(value: A): Result<A, never> => ({ ok: true, value })export const err = <E>(error: E): Result<never, E> => ({ ok: false, error })
// `unknown` in R means "needs nothing": unknown & X is X, so requirements combine with &.export interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>> // Makes `yield* program` work inside gen. It yields the program itself and returns its value. [Symbol.iterator](): Generator<Program<unknown, E, R>, A, unknown>}
function make<A, E, R>(run: (env: R) => Promise<Result<A, E>>): Program<A, E, R> { const self: Program<A, E, R> = { run, *[Symbol.iterator]() { // The one cast: gen sends the program's value back in, and the type system cannot see that. return (yield self) as A }, } return self}
export const succeed = <A>(value: A): Program<A> => make(async () => ok(value))export const fail = <E>(error: E): Program<never, E> => make(async () => err(error))export const sync = <A>(thunk: () => A): Program<A> => make(async () => ok(thunk()))export const promise = <A, E>(thunk: () => Promise<A>, onError: (cause: unknown) => E): Program<A, E> => make(async () => { try { return ok(await thunk()) } catch (cause) { return err(onError(cause)) } })
export const map = <A, B, E, R>(p: Program<A, E, R>, f: (a: A) => B): Program<B, E, R> => make(async (env) => { const r = await p.run(env) return r.ok ? ok(f(r.value)) : r })
export const flatMap = <A, B, E, R, E2, R2>( p: Program<A, E, R>, f: (a: A) => Program<B, E2, R2>,): Program<B, E | E2, R & R2> => make<B, E | E2, R & R2>(async (env) => { const r = await p.run(env) return r.ok ? f(r.value).run(env) : r })
type ErrorOf<Y> = Y extends Program<unknown, infer E, never> ? E : never// Not distributive on purpose: several contravariant candidates for R are combined with &.type EnvOf<Y> = [Y] extends [Program<unknown, unknown, infer R>] ? R : never
// Do-notation: A is the return type, E and R are the union and the intersection of every yielded program.export function gen<Y extends Program<unknown, unknown, never>, A>( body: () => Generator<Y, A, unknown>,): Program<A, ErrorOf<Y>, EnvOf<Y>>export function gen(body: () => Generator<Program<unknown, unknown, object>, unknown, unknown>) { return make(async (env: object) => { const it = body() let step = it.next() while (!step.done) { const r = await step.value.run(env) if (!r.ok) { it.return(undefined) return r } step = it.next(r.value) } return ok(step.value) })}
export const service = <S>() => <K extends string>(key: K): Program<S, never, { readonly [P in K]: S }> => make(async (env) => ok(env[key]))
type Tagged = { readonly _tag: string }type TagOf<E> = E extends Tagged ? E["_tag"] : neverconst hasTag = (e: unknown, tag: string): e is Tagged => typeof e === "object" && e !== null && "_tag" in e && e._tag === tag
export function catchTag<A, E, R, T extends TagOf<E>, B, E2, R2>( p: Program<A, E, R>, tag: T, handler: (error: Extract<E, { readonly _tag: T }>) => Program<B, E2, R2>,): Program<A | B, Exclude<E, { readonly _tag: T }> | E2, R & R2>// The loose implementation signature is where the types stop checking, so keep it tiny.export function catchTag( p: Program<unknown, unknown, object>, tag: string, handler: (error: unknown) => Program<unknown, unknown, object>,): Program<unknown, unknown, object> { return make(async (env: object) => { const r = await p.run(env) return !r.ok && hasTag(r.error, tag) ? handler(r.error).run(env) : r })}
export function provide<A, E, R, P extends Partial<R>>( p: Program<A, E, R>, services: P,): Program<A, E, Omit<R, keyof P>>export function provide(p: Program<unknown, unknown, object>, services: object): Program<unknown, unknown, object> { return make((env: object) => p.run({ ...env, ...services }))}
// R must be satisfied. NoInfer keeps env from widening R: the program decides what is needed.export const run = <A, E, R>(p: Program<A, E, R>, env: NoInfer<R>): Promise<Result<A, E>> => p.run(env)The composition root builds the real services once and runs the program for each job:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }interface Program<out A, out E = never, in R = unknown> { readonly run: (env: R) => Promise<Result<A, E>>}declare const run: <A, E, R>(p: Program<A, E, R>, env: NoInfer<R>) => Promise<Result<A, E>>interface Job { readonly id: string}interface Env { readonly clock: { now(): number } readonly notifier: { send(text: string): Promise<void> } readonly store: { save(jobId: string, outcome: string, at: number): Promise<void> }}declare const handleJobSafely: (job: Job) => Program<"done" | "invalid" | "retry", { readonly _tag: string }, Env>declare const nextJob: () => Promise<Job | null>
const env: Env = { clock: { now: () => Date.now() }, notifier: { send: async (text) => void (await fetch("https://hooks.example.com/relay", { method: "POST", body: text })) }, store: { save: async (id, outcome, at) => void console.log(id, outcome, at) },}
for (let job = await nextJob(); job !== null; job = await nextJob()) { const result = await run(handleJobSafely(job), env) if (!result.ok) { console.error(`job ${job.id} failed: ${result.error._tag}`) process.exit(1) } console.log(`job ${job.id}: ${result.value}`)}Replace the declares with imports from ./program.ts and your own handler, and the fakes with a
real queue and database. Real clocks, networks and consoles appear only in this file. Everything
above the for loop is a value.
- A
Program<A, E, R>is a value: a description of work with a resultA, failuresEand requirementsR. Building it runs nothing. flatMapandgenjoin programs: errors become a union, requirements an intersection.geninfers both from theyield*lines.catchTaghandles one tagged error and removes it fromE. A typo in the tag does not compile.service(key)adds a requirement,provideremoves it, andrunneeds the rest. A missing service is a compile error.- The model is a teaching size. It shows where types do the work, not what a production runtime needs.
Where to go from here
Section titled “Where to go from here”This is the last lesson of the core course. You can now read a TypeScript codebase from a config loader to a type-level router to a functional core, and write each part yourself.
The Extras modules go deeper into the places Relay meets the outside world. Take them in any order:
- Testing: test runners, fakes, snapshots and the type-level test habits you used in this module.
- Declarations:
.d.tsfiles, typing untyped packages, and publishing types. - Concurrency: promises, workers, queues and the failure modes that appear when work overlaps.
- Networking: HTTP clients and servers, streaming, timeouts and retries on a real wire.
- Operating system: files, processes, signals and the environment, the layer under Relay’s shell.
Further reading
Section titled “Further reading”- Narrowing: discriminated unions and exhaustiveness checking.
- Iterators and generators: generator functions and
yield.