A typed pipe and flow
Relay’s failure report has three steps: keep the failed events, turn each into a line of text, take the first three. Written as plain calls, the first step ends up innermost:
declare const events: readonly string[]declare function onlyFailed(xs: readonly string[]): string[]declare function format(xs: readonly string[]): string[]declare function firstThree(xs: readonly string[]): string[]
const report = firstThree(format(onlyFailed(events)))You read it right to left, from the middle out. Add a fourth step and you have to rewrite the whole
nesting. pipe(events, onlyFailed, format, firstThree) reads in the order the data moves. The
runtime part is trivial. This lesson is about the types: each function’s output must be checked
against the next function’s input.
Why a variadic signature isn’t enough
Section titled “Why a variadic signature isn’t enough”The obvious signature accepts any list of functions:
function pipeLoose(value: unknown, ...fns: Array<(x: any) => any>): any { return fns.reduce((acc, fn) => fn(acc), value)}
const n = pipeLoose(1, (s: string) => s.length) // any, and a number was passed to a string functionArray<(x: any) => any> describes a list where every function is independent. It can’t say “the
second function’s input is the first function’s output”, because that relates neighbors in a list
of unknown length, and the result is any. Every function in the chain is unchecked.
One overload per length
Section titled “One overload per length”Overloads (from the functions lesson) let you write one signature for each number of steps. In each one, the output type of a step is the input type of the next:
function pipe<A>(a: A): Afunction pipe<A, B>(a: A, ab: (a: A) => B): Bfunction pipe<A, B, C>(a: A, ab: (a: A) => B, bc: (b: B) => C): Cfunction pipe<A, B, C, D>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): Dfunction pipe(value: unknown, ...fns: Array<(x: unknown) => unknown>): unknown { return fns.reduce((acc, fn) => fn(acc), value)}
const r = pipe(1, (n) => n + 1, String) // string
// @ts-expect-error: Argument of type 'number' is not assignable to parameter of type 'string'pipe(1, (s: string) => s)Callers see only the overloads. The last signature is the implementation, and it is hidden. It can
use unknown inside because the overloads already guarantee that the chain lines up. The cost is
one overload per arity, written out by hand. Libraries stop at around ten. Relay’s exercise stops at
six: a longer chain is a hint to name an intermediate step.
TypeScript tries the overloads in order and takes the first that fits. For pipe(1, f, g) that is
the three-argument one: A is number from the value, B comes from f’s return, and g must
accept B.
Inference runs left to right
Section titled “Inference runs left to right”The reason (n) => n + 1 needs no annotation in the example above: TypeScript infers A from the
first argument, uses it as the contextual type of the first function’s parameter, takes B from
that function’s return, and so on down the chain.
declare function pipe<A, B, C>(a: A, ab: (a: A) => B, bc: (b: B) => C): C
const lengths = pipe( "job-42", (id) => id.split("-"), // id: string (parts) => parts.length, // parts: string[])// lengths: numberEach callback gets its parameter type from the step before it. Hover a parameter in the editor and you see the type that flowed in. A mistake shows up at the step where the types stop matching, not at the end of the chain.
flow returns a function
Section titled “flow returns a function”pipe runs a chain on a value now. flow builds the chain and returns it as a function. It has the
same overloads, minus the starting value, and the first function may take several arguments:
function flow<A extends unknown[], B>(ab: (...a: A) => B): (...a: A) => Bfunction flow<A extends unknown[], B, C>(ab: (...a: A) => B, bc: (b: B) => C): (...a: A) => Cfunction flow<A extends unknown[], B, C, D>( ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D,): (...a: A) => Dfunction flow( first: (...args: never[]) => unknown, ...rest: Array<(x: unknown) => unknown>): (...args: never[]) => unknown { return (...args) => rest.reduce((acc, fn) => fn(acc), first(...args))}
const parseHex = flow((raw: string, radix: number) => parseInt(raw, radix), (n) => n + 1, String)// (raw: string, radix: number) => stringA extends unknown[] is the rest-tuple parameter from the last lesson. It
carries the first function’s whole argument list to the result. Use flow when you want to name a
reusable step (const parseHex = flow(...)) and pipe when you have the data in hand.
Data-last helpers
Section titled “Data-last helpers”pipe works best with functions that take their data last: map(f) returns a function that
waits for the array. That is the curried shape from the previous lesson, and it is what makes each
step a one-argument function:
const map = <A, B>(f: (a: A) => B) => (xs: readonly A[]): B[] => xs.map((x) => f(x))
const take = <A>(n: number) => (xs: readonly A[]): A[] => xs.slice(0, n)
declare function pipe<A, B, C>(a: A, ab: (a: A) => B, bc: (b: B) => C): C
const firstTwo = pipe( [1, 2, 3], map((n) => n * 10), // n: number take(2),)// number[]take(2) has no way to know its element type when you write it. It is a generic function whose A
is filled in from where it is used: the position in pipe where a (b: number[]) => C is
expected. That inference from the expected type is what lets take(2) and map((n) => ...) work
without any annotation.
A filter that narrows
Section titled “A filter that narrows”An ordinary filter keeps the array’s element type, even if the callback proves something about it.
Relay’s events are a union, and a report of failures should be a list of JobFailed. The fix is an
overload for type predicates (e is JobFailed, from M1’s narrowing lesson):
interface JobStarted { readonly _tag: "JobStarted" readonly jobId: string}interface JobFailed { readonly _tag: "JobFailed" readonly jobId: string readonly reason: string}type JobEvent = JobStarted | JobFailed
function filter<A, B extends A>(pred: (a: A) => a is B): (xs: readonly A[]) => B[]function filter<A>(pred: (a: A) => boolean): (xs: readonly A[]) => A[]function filter<A>(pred: (a: A) => boolean): (xs: readonly A[]) => A[] { return (xs) => xs.filter((x) => pred(x))}
declare function pipe<A, B>(a: A, ab: (a: A) => B): Bdeclare const events: readonly JobEvent[]
const failures = pipe( events, filter((e): e is JobFailed => e._tag === "JobFailed"),) // JobFailed[]
const started = pipe( events, filter((e) => e._tag === "JobStarted"),) // JobEvent[]: a plain boolean callback doesn't narrowOverload order matters. The predicate form comes first, so a callback that returns a is B matches
it. A plain boolean callback doesn’t, and falls through to the second. If the order were reversed,
the general overload would accept everything and B would never be used.
Exercise
Section titled “Exercise”Implement pipe (a value and up to six functions), flow, map, filter with its predicate
overload, and take. Then use them in summarize. The starter’s pipe runs correctly but has
type any everywhere, and its filter doesn’t narrow, so the tests’ type checks fail.
- Nested calls read from the inside out.
pipe(value, f, g, h)reads in the order the data moves. - A variadic
(...fns: Array<(x: any) => any>)can’t relate neighbors, so it types nothing. Write one overload per arity: each step’s output is the next step’s input. - The implementation signature is hidden from callers, so it can use
unknowninternally. - Inference runs left to right, so callbacks inside
pipeget contextual parameter types. flowreturns the composed function. Its first step carries the argument list asA extends unknown[].- Make helpers data-last so each step has one parameter. Give
filtera type-predicate overload, listed first, so it narrows.
Further reading
Section titled “Further reading”- Handbook: More on Functions: function overloads and generic signatures.
- Handbook: Generics: generic constraints.