Option and Result as values
To verify a webhook, Relay looks up the secret for its source, reads the signature header, and
compares. Two things can go wrong before the comparison: no secret is registered, or the header is
missing. In M1-M5 style that is if (secret === undefined) throw ... twice, and nothing in the
function’s type says it can fail.
This lesson turns both problems into values. Absence becomes an Option. Failure becomes the
Result from generics. Because they are values, they can be passed, returned,
and chained.
Option for absence
Section titled “Option for absence”type Option<A> = { readonly _tag: "Some"; readonly value: A } | { readonly _tag: "None" }const some = <A>(value: A): Option<A> => ({ _tag: "Some", value })const none: Option<never> = { _tag: "None" }
declare const secrets: Readonly<Record<string, string>>
const findSecret = (source: string): Option<string> => { const s = secrets[source] // string | undefined return s === undefined ? none : some(s)}Option<A> is a discriminated union: a value, or
nothing. That raises the fair question of why not use A | undefined. There is a case where the
two differ:
type Option<A> = { readonly _tag: "Some"; readonly value: A } | { readonly _tag: "None" }declare const some: <A>(value: A) => Option<A>declare const none: Option<never>
// Option nests: "a setting that is present but itself unset" is representableconst present: Option<Option<number>> = some(none)const absent: Option<Option<number>> = none
// undefined does not: both cases collapse into the same valuetype Flat = (number | undefined) | undefined // number | undefinedA Map<string, number | undefined> lookup that returns undefined cannot say whether the key is
missing or stored as undefined. With Option<Option<number>> the two are different values. When
that distinction never matters, A | undefined is simpler, and that is most of the time.
Result for failure
Section titled “Result for failure”Result<A, E> is the same idea with a reason attached. Relay’s version keeps the M3 shape:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
type VerifyError = | { readonly _tag: "UnknownSource"; readonly source: string } | { readonly _tag: "MissingSignature" } | { readonly _tag: "BadSignature" }
declare function verify(w: { readonly source: string; readonly body: string }): Result<true, VerifyError>The failure is in the return type. A caller cannot use the value without first checking ok, so
the compiler forces the check that throw lets you forget (error unions
covers the same idea with classes).
map, flatMap and getOrElse
Section titled “map, flatMap and getOrElse”Checking ok after every call brings back the nesting you wanted to avoid. Three combinators
cover most cases. All are data-last, so they sit in a pipe (lesson 4):
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }const ok = <A>(value: A): Result<A, never> => ({ ok: true, value })const err = <E>(error: E): Result<never, E> => ({ ok: false, error })
// change the success, leave a failure aloneconst map = <A, B>(f: (a: A) => B) => <E>(r: Result<A, E>): Result<B, E> => r.ok ? ok(f(r.value)) : r
// the next step can fail too; the first error winsconst flatMap = <A, B, F>(f: (a: A) => Result<B, F>) => <E>(r: Result<A, E>): Result<B, E | F> => r.ok ? f(r.value) : r
// leave the Result world with a fallbackconst getOrElse = <E, B>(onErr: (e: E) => B) => <A>(r: Result<A, E>): A | B => r.ok ? r.value : onErr(r.error)map takes a function that cannot fail. flatMap takes one that can, and the error type grows to
E | F. If you used map with a failing function you would get Result<Result<B, F>, E>, which
is why flatMap exists. Option has the same three, plus fromNullable, which is where values
from the outside world enter:
type Option<A> = { readonly _tag: "Some"; readonly value: A } | { readonly _tag: "None" }const some = <A>(value: A): Option<A> => ({ _tag: "Some", value })const none: Option<never> = { _tag: "None" }
const fromNullable = <A>(a: A | null | undefined): Option<A> => (a === null || a === undefined ? none : some(a))
declare const headers: Readonly<Record<string, string>>const signature = fromNullable(headers["x-signature"]) // Option<string>(You may know map on arrays and promises. All of them are “apply a function inside a context”,
which is what the word functor names. You do not need the word to use the tool.)
match takes one handler per case and returns one value. It is the exit from Option or Result
when the next step is not another combinator, such as building an HTTP response:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }
const match = <A, E, B>(onErr: (e: E) => B, onOk: (a: A) => B) => (r: Result<A, E>): B => r.ok ? onOk(r.value) : onErr(r.error)
declare const verified: Result<{ readonly id: string }, { readonly _tag: "BadSignature" }>const status = match( () => 401, () => 202,)(verified)Both handlers must return the same type, and neither case can be forgotten.
Exercise
Section titled “Exercise”Implement the combinators in O and R, then use them: findSecret returns an Option, and
verify turns it into a Result and checks the x-signature header in one pipe. The source is
checked before the header.
Option<A>is a value or nothing. UnlikeA | undefined, it nests:Option<Option<A>>keeps “present but empty” apart from “absent”.Result<A, E>puts the failure in the type, so the compiler makes callers handle it.mapchanges the success,flatMapchains a step that can fail (errors add up asE | F),getOrElseandmatchleave the wrapper.fromNullableis the entry point for values from records, headers and environment variables.- Data-last combinators fit in
pipe. Keepthrowfor bugs, not for expected failures.
Further reading
Section titled “Further reading”- Narrowing: discriminated unions and exhaustiveness checking.