Strongly Typed Variadic Functions in TypeScript
Type pipe and compose with overloads so TypeScript checks every connection in pipelines of different lengths.
In Strongly Typed Function Composition, we built pipe2, a typed pipe that connects exactly two functions. This was useful, but each call could only connect two functions. In this post, we’ll take the next step to answer the question: how do we type pipe and compose that take a variable number of functions while having TypeScript check every connection between them?
Quick refresher
To warm ourselves up a bit, we’ll take a quick look at the aforementioned pipe2 function.
pipe2 takes two functions and returns a new function that runs them in order. Its three type parameters link them together: A goes in, B passes between them, and C comes out.
const pipe2 =
<A, B, C>(first: (value: A) => B, second: (value: B) => C) =>
(value: A): C =>
second(first(value));
const addTen = (value: number) => value + 10;
const double = (value: number) => value * 2;
console.log(pipe2(addTen, double)(5)); // 30Ctrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
Next, let’s acquaint ourselves with a few utility functions, including the illustrious trace. We’ll use it to log labelled values at different points in the pipeline. Logging is a side effect, but trace returns the value unchanged.
const trace =
(label: string) =>
<T>(value: T): T => {
console.log(label, "::", value);
return value;
};
const trim = (value: string) => value.trim();
const toLowerCase = (value: string) => value.toLowerCase();
const length = (value: string) => value.length;
const atMost = (limit: number) => (count: number) => count <= limit;
const addTen = (x: number) => x + 10;
const double = (x: number) => x * 2;
console.log(trim(' A short summary ')); // 'A short summary'
console.log(length('hello')); // 5
console.log(atMost(160)(5)); // true
trace('length')(5); // length :: 5Ctrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
pipe2, check. Utility functions, check. Now, let’s see the limitations of pipe2 firsthand. We’ll illustrate this by checking whether a trimmed summary fits in 160 characters. Here, we nest one pipe2 inside another.
import { pipe2 } from './pipe2';
import { trim, length, atMost } from './functions';
const fitsSummary = pipe2(trim, pipe2(length, atMost(160)));
// (value: string) => boolean
console.log(fitsSummary(' ' + 'x'.repeat(160) + ' ')); // true
console.log(fitsSummary('x'.repeat(161))); // falseCtrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
It works, but every new step means another layer. We can get around this by extending pipe and compose to accept more than two functions, while still having TypeScript check the types between transformations.
Extending to variadic composition
At runtime, .reduce() and .reduceRight() can hand each function’s result to the next, meaning that we can use both to create versions of pipe and compose that allow us to combine multiple layers of logic.
Our goal is to find a way to type this that lets us benefit from TypeScript’s type system while also enjoying the fruits of composition.
For our first pass, we’ll type the rest parameter ...fns as an array of functions.
import { trim, length, atMost } from './functions';
const pipe =
(...fns: Array<(value: any) => any>) =>
(initialValue: any) =>
fns.reduce((acc, fn) => fn(acc), initialValue);
const fitsSummary = pipe(trim, length, atMost(160));
// (initialValue: any) => any
const broken = pipe(length, trim, atMost(160));
// (initialValue: any) => any
console.log(fitsSummary(' A short summary ')); // true
// Uncomment to see the invalid order fail at runtime:
// console.log(broken(' A short summary '));Ctrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
This compiles, but it doesn’t help us much. Both pipelines get the same type, so TypeScript can’t tell the working one from the broken one.
This is because Array<(value: any) => any> gives every function the same input and return types. It forgets that trim returns a string and length expects one. The connections we so badly want are gone.
We can’t swap any for the safer unknown either. A (value: unknown) => unknown has to accept anything, so when TypeScript sees trim, which only accepts strings, it rejects it.
Won’t you help me cure this, overloads?
With pipe2, we used a separate type for every connection: A, B, and C. With pipe and compose, we can lean on TypeScript’s overloads feature.
Overloads give us a vehicle for writing out one call signature for each number of functions we wish to support. Once that’s wired up, TypeScript will automatically pick the signature that matches the call.
import { trim, length, atMost } from './functions';
type Pipe = {
<A, B>(ab: (a: A) => B): (a: A) => B;
<A, B, C>(ab: (a: A) => B, bc: (b: B) => C): (a: A) => C;
<A, B, C, D>(ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): (a: A) => D;
<A, B, C, D, E>(
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E
): (a: A) => E;
};
const pipe: Pipe =
(...fns: Array<(value: any) => any>) =>
(value: any) =>
fns.reduce((acc, fn) => fn(acc), value);
const fitsSummary = pipe(trim, length, atMost(160));
console.log(fitsSummary(' A short summary ')); // trueCtrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
These four call signatures describe ways to call the same pipe function, with each one covering a different number of steps. If you inspect the signature, you’ll see each one repeat the trick that made pipe2 work.
Let’s consider the three-function signature associated with pipe(trim, length, atMost(160)). TypeScript matches each function to a parameter and fills in the letters:
abistrim, soAisstringandBisstring.bcislength, soBisstringandCisnumber.cdisatMost(160), soCisnumberandDisboolean.
The shared B and C check the connections.
The three-function overload tells TypeScript that we want to go from A to D. The function we get back is (a: A) => D, which here works out to (a: string) => boolean.
The implementation still uses any to run the steps, but thanks to the overloads, we’re leveraging TypeScript’s abilities to check the connections at the call site.
import { pipe } from './pipe';
import { trim, length, atMost, trace } from './functions';
const fitsSummary = pipe(trim, length, atMost(160));
// (a: string) => boolean
const fitsSummaryTraced = pipe(trim, trace('trimmed'), length, atMost(160));
// (a: string) => boolean
console.log(fitsSummary(' A short summary ')); // true
console.log(fitsSummaryTraced(' A short summary '));
// trimmed :: A short summary
// trueCtrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
Adding trace gives us four steps, so TypeScript selects the four-function overload. The new step logs the string and passes it on unchanged, so the pipeline still accepts a string and returns a boolean.
And if we swap two functions, TypeScript catches it:
import { pipe } from './pipe';
import { trim, length, atMost } from './functions';
// Swap length and trim to clear the type error.
const broken = pipe(length, trim, atMost(160));Ctrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
From pipe to compose
compose gets the same treatment. Its signatures match Pipe’s, with the parameters listed in reverse. The rightmost function runs first.
import { trim, length, atMost, trace } from './functions';
type Compose = {
<A, B>(ab: (a: A) => B): (a: A) => B;
<A, B, C>(bc: (b: B) => C, ab: (a: A) => B): (a: A) => C;
<A, B, C, D>(cd: (c: C) => D, bc: (b: B) => C, ab: (a: A) => B): (a: A) => D;
<A, B, C, D, E>(
de: (d: D) => E,
cd: (c: C) => D,
bc: (b: B) => C,
ab: (a: A) => B
): (a: A) => E;
};
const compose: Compose =
(...fns: Array<(value: any) => any>) =>
(value: any) =>
fns.reduceRight((acc, fn) => fn(acc), value);
const fitsSummary = compose(atMost(160), length, trim);
// (a: string) => boolean
const fitsSummaryTraced = compose(atMost(160), length, trace('trimmed'), trim);
// (a: string) => boolean
console.log(fitsSummary(' A short summary ')); // true
console.log(fitsSummary('x'.repeat(161))); // false
console.log(fitsSummaryTraced(' A short summary '));
// trimmed :: A short summary
// trueCtrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
compose uses .reduceRight() to run the same steps as pipe(trim, length, atMost(160)).
The trace version has four steps, just like our pipe example. We can also swap trim and length to see compose reject an incompatible connection. For those interested in seeing this error surface, I encourage you to run the code block below.
import { compose } from './compose';
import { trim, length, atMost } from './functions';
// Swap trim and length to clear the type error.
const broken = compose(atMost(160), trim, length);Ctrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
An exercise in progressive overloads
Our overloads have a limit. They stop at four functions. Pass in five, and TypeScript tells us Expected 1-4 arguments, but got 5.
For a longer pipeline, we can add more signatures or nest pipe or compose calls. Function composition is associative, so how we group the functions doesn’t change the result.
Here’s your chance to try a little progressive overload. Add a five-function signature to both Pipe and Compose below. The utility functions are imported so you can focus on the signatures.
Both five-function calls start with type errors. The runtime already handles five steps, so the challenge is to make TypeScript accept the calls and infer (a: string) => boolean for both functions. Once that works, swap two incompatible steps and check that TypeScript still catches the mistake.
import { trim, toLowerCase, trace, length, atMost } from './functions';
type Pipe = {
// Add a five-function overload for pipe here.
<A, B>(ab: (a: A) => B): (a: A) => B;
<A, B, C>(ab: (a: A) => B, bc: (b: B) => C): (a: A) => C;
<A, B, C, D>(ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): (a: A) => D;
<A, B, C, D, E>(
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E
): (a: A) => E;
};
const pipe: Pipe =
(...fns: Array<(value: any) => any>) =>
(value: any) =>
fns.reduce((acc, fn) => fn(acc), value);
type Compose = {
// Add a five-function overload for compose here.
<A, B>(ab: (a: A) => B): (a: A) => B;
<A, B, C>(bc: (b: B) => C, ab: (a: A) => B): (a: A) => C;
<A, B, C, D>(cd: (c: C) => D, bc: (b: B) => C, ab: (a: A) => B): (a: A) => D;
<A, B, C, D, E>(
de: (d: D) => E,
cd: (c: C) => D,
bc: (b: B) => C,
ab: (a: A) => B
): (a: A) => E;
};
const compose: Compose =
(...fns: Array<(value: any) => any>) =>
(value: any) =>
fns.reduceRight((acc, fn) => fn(acc), value);
// Both calls need a five-function overload.
const fitsSummary = pipe(trim, toLowerCase, trace('normalized'), length, atMost(160));
const fitsSummaryWithCompose = compose(atMost(160), length, trace('normalized'), toLowerCase, trim);
const summary = ' A short summary ';
console.log(fitsSummary(summary)); // true
console.log(fitsSummaryWithCompose(summary)); // trueCtrl+Enter or ⌘Enter runs the code. Tab indents inside the editor; press Ctrl+M (macOS: Ctrl+Shift+M) to make Tab move focus instead. Reset is undoable with Ctrl+Z or ⌘Z.
Recap, thank you!
And thus concludes this segment on strongly typed variadic functions in TypeScript! We’ve built pipe and compose without a third-party library, all while keeping the type connections intact. When we need a longer pipeline, we can add another overload. As always, thanks for reading! I sincerely hope you’ve gained something from checking it out.