Type-Safe Left-To-Right Pipe Composition

Chain data transformations left to right with typed function overloads so each stage infers its parameter from the previous return value without any.

TypescriptData Integrity

Code

typescriptsnippet
23 lines
function pipe<A, B>(value: A, fn1: (a: A) => B): B;
function pipe<A, B, C>(value: A, fn1: (a: A) => B, fn2: (b: B) => C): C;
function pipe<A, B, C, D>(
  value: A,
  fn1: (a: A) => B,
  fn2: (b: B) => C,
  fn3: (c: C) => D,
): D;
function pipe(value: unknown, ...fns: Array<(arg: unknown) => unknown>): unknown {
  return fns.reduce((acc, fn) => fn(acc), value);
}

// Each stage infers its argument type directly from the previous return type
const report = pipe(
  '  alpha, beta , gamma , beta ',
  (raw) => raw.split(',').map((s) => s.trim()).filter(Boolean),
  (items) => new Set(items),
  (unique) => `${unique.size} tags: ${[...unique].join('|')}`,
);

console.log('pipe result:', report);
const doubled = pipe(7, (n) => n * 2, (n) => n + 1);
console.log('math pipe:', doubled);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

pipe result: 3 tags: alpha|beta|gamma
math pipe: 15

What the code does

The code’s whole job belongs to the function pipe.

What to watch for

  • The import surface (if any) is all standard library, all versioned with the language itself.

Applying it

Entry signature: function pipe(value: unknown, ...fns: Array<(arg: unknown)

The run prints pipe result:, math pipe: — each prefix names the step that produced it.

Statements that matter

return fns.reduce((acc, fn) => fn(acc), value);
function pipe<A, B, C>(value: A, fn1: (a: A) => B, fn2: (b: B) => C): C;
const doubled = pipe(7, (n) => n * 2, (n) => n + 1);

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `pipe` at load time.