← 中文资源

简体中文版本

类型安全的从左到右 pipe 组合函数

用泛型重载编写从左到右的 pipe 组合函数,让每一阶段自动从上一阶段的返回类型推导参数类型,无需借助 any 或手动标注中间变量。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

逻辑集中在函数 pipe里。

使用要点

  • 复制、运行:标准库能接住文件里的每一个调用。
  • 演示输出是带标签的(pipe result:、math pipe:),每个操作都会留下自己的一行标注。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 pipe。

主签名形如 function pipe(value: unknown, ...fns: Array<(arg: unknown)

核心语句

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);

代码示例

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);