3 minFunctional Programming, with Types, part 3

Strongly Typed Function Composition

Build reusable functions with pipe2 and compose2 while TypeScript checks the types between each step.

Function composition lets us build new functions by passing one function’s result to the next. In the currying post, we chose a transformation before supplying the data. Here, we’ll connect transformations while keeping their types intact.

One transformation after another

Let’s start with two functions we can combine.

Apply transformations in sequenceTypeScript 5.9.3 · strict
const addTen = (value: number) => value + 10;
const double = (value: number) => value * 2;

const values = [5];

console.log(values.map(addTen).map(double)); // [30]
console.log(values.map((value) => double(addTen(value)))); // [30]

Both give us [30]. First we add ten, then we double the result. The second version combines those operations in a single callback. What you may not have realized is that we just tested out the composition law from algebra.

(f∘g)(x)=f(g(x))(f \circ g)(x) = f(g(x))

In the code example, addTen would be g and double would be f. This is relevant because, when composing pure functions together, we can model our software like a basic algebra problem.

Enough of the math talk though, let’s move forward and create a new function that performs these transformations in one go.

Name a composed functionTypeScript 5.9.3 · strict
const addTen = (value: number) => value + 10;
const double = (value: number) => value * 2;

const addTenThenDoubleExplicit = (value: number) => double(addTen(value));

console.log(addTenThenDoubleExplicit(5)); // 30

Now we have a function we can call directly or pass to .map(). While this is useful, we could wire up utility functions that allow us to create functions like addTenThenDoubleExplicit without having to write functions like Russian nesting dolls.

Matryoshka doll

Connecting two functions with pipe2

pipe2 takes two functions and returns a function that runs them in the order we pass them in.

Build a function with pipe2TypeScript 5.9.3 · strict
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;

const addTenThenDouble = pipe2(addTen, double);

console.log(addTenThenDouble(5)); // 30

A is the input type, and C is the return type. The shared B connects the first function’s output to the second function’s input. That’s how TypeScript checks that the two functions fit together.

Here, all three types are number. TypeScript infers (value: number) => number for addTenThenDouble, so we can reuse it wherever we need that transformation.

The same steps with compose2

compose2 lets us write the functions in reverse order, or bottom-up, matching the composition law we looked at earlier. The rightmost function runs first.

Build a function with compose2TypeScript 5.9.3 · strict
const compose2 =
  <A, B, C>(second: (value: B) => C, first: (value: A) => B) =>
  (value: A): C =>
    second(first(value));

const addTen = (value: number) => value + 10;
const double = (value: number) => value * 2;

const addTenThenDoubleWithCompose = compose2(double, addTen);

console.log(addTenThenDoubleWithCompose(5)); // 30

The implementation is the same. We just changed the order of the parameters, so compose2(double, addTen) runs the same steps as pipe2(addTen, double).

When types aren’t enough

The order we pass functions in very much matters though. pipe2(double, addTen)(5) gives us 20. Both orders accept and return numbers, so both type-check. To ensure we’re getting the output we intend, we can use a test to check our result.

Run the test below. Swap addTen and double, then run it again. The types still fit, but we’ll see the assertion fail because the result is 20.

Test the intended order with node:assertTypeScript 5.9.3 · strict · with pipe2.ts
import { strictEqual } from 'node:assert';
import { pipe2 } from './pipe2';

const addTen = (value: number) => value + 10;
const double = (value: number) => value * 2;

const addTenThenDouble = pipe2(addTen, double);

strictEqual(addTenThenDouble(5), 30);
console.log('Test passed.');

// Swap addTen and double above, then run the test again.

TypeScript is very useful, but it’s still important to test our logic and verify that our code behaves as intended. As Eric Elliott so eloquently puts it, “Type correctness does not guarantee program correctness.”

When the types change

In the currying post, maxLength(160) counted characters and compared the count with a limit. Let’s split those jobs into separate functions.

Check a summaryTypeScript 5.9.3 · strict · with pipe2.ts
import { pipe2 } from './pipe2';

const length = (value: string) => value.length;
const atMost = (limit: number) => (count: number) => count <= limit;

const fitsSummary = pipe2(length, atMost(160));
// (value: string) => boolean

console.log(fitsSummary('x'.repeat(160))); // true
console.log(fitsSummary('x'.repeat(161))); // false

TypeScript infers A as string, B as number, and C as boolean. The result is a reusable function that accepts text and tells us whether it fits.

Now let’s swap the steps. Choose Edit this code to see the type error, then swap the functions back to clear it.

An incompatible connectionTypeScript 5.9.3 · strict · with pipe2.ts
import { pipe2 } from './pipe2';

const length = (value: string) => value.length;
const atMost = (limit: number) => (count: number) => count <= limit;

// Swap the functions back to length, atMost(160) to clear the type error.
const broken = pipe2(atMost(160), length);

TypeScript rejects this connection. atMost(160) returns a boolean, while length accepts a string. We get the error when we combine the functions, before we pass in any data.

We can also use the function we’ve built as a step in another composition. If we want to ignore spaces at either end of the summary, we can trim the text first.

Reuse a summary checkTypeScript 5.9.3 · strict · with pipe2.ts
import { pipe2 } from './pipe2';

const length = (value: string) => value.length;
const atMost = (limit: number) => (count: number) => count <= limit;
const trim = (value: string) => value.trim();

const fitsSummary = pipe2(length, atMost(160));
const fitsTrimmedSummary = pipe2(trim, fitsSummary);

const padded = '  ' + 'x'.repeat(160) + '  ';

console.log(fitsSummary(padded)); // false
console.log(fitsTrimmedSummary(padded)); // true

fitsSummary already handles the count and the comparison. We can reuse it alongside trim, and TypeScript still infers (value: string) => boolean for the function we get back.

Try it yourself

Here’s the code in one place. Uncomment the last line to see TypeScript reject the reversed steps. Try combining trim and fitsSummary with compose2 as well.

Compose two typed transformationsTypeScript 5.9.3 · strict
const pipe2 =
  <A, B, C>(first: (value: A) => B, second: (value: B) => C) =>
  (value: A): C =>
    second(first(value));

const compose2 =
  <A, B, C>(second: (value: B) => C, first: (value: A) => B) =>
  (value: A): C =>
    second(first(value));

const addTen = (value: number) => value + 10;
const double = (value: number) => value * 2;

const values = [5];
console.log(values.map(addTen).map(double)); // [30]
console.log(values.map(value => double(addTen(value)))); // [30]

const addTenThenDouble = pipe2(addTen, double);
const addTenThenDoubleWithCompose = compose2(double, addTen);

console.log(addTenThenDouble(5)); // 30
console.log(addTenThenDoubleWithCompose(5)); // 30
console.log(pipe2(double, addTen)(5)); // 20

const length = (value: string) => value.length;
const atMost = (limit: number) => (count: number) => count <= limit;
const trim = (value: string) => value.trim();

const fitsSummary = pipe2(length, atMost(160));
const fitsTrimmedSummary = pipe2(trim, fitsSummary);
const padded = "  " + "x".repeat(160) + "  ";

console.log(fitsSummary("x".repeat(160))); // true
console.log(fitsSummary("x".repeat(161))); // false
console.log(fitsSummary(padded)); // false
console.log(fitsTrimmedSummary(padded)); // true

// Uncomment to see TypeScript reject incompatible steps:
// const broken = pipe2(atMost(160), length);

And thus concludes our post! We’ve built functions that we can reuse on their own or pass into another composition. Each time, TypeScript checks the connection and infers the input and return types of the function we build. Useful stuff! In the post on variadic functions, we extend pipe and compose to accept more than two functions.

Thomas Greco writes about software engineering, life, and what he’s learning and building.