You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中为transduce函数正确定义类型?

修正Transduce函数的TypeScript类型定义问题

我实现了一个最小化的transduce,但输出类型存在错误。当前测试中,transduceNum的类型被推断为unknown,而预期应该是Set<number>(和单独使用map+toSet的mapNum一致),同时需要保留现有的错误提示能力(比如传入类型不匹配时的报错)。

/* transducer */
const map =
  <VOut,VIn,KIn>(mapper: (v: VIn, k?:KIn) => VOut) =>
    <A, R>(nextReducer: (acc: A, v: VOut, k?:KIn) => R) =>
      <V extends VIn>(acc: A, value: V, key?:KIn) => nextReducer(acc, mapper(value,key), key);

/* final reducer */
const toSet = <V,K,A>(acc:A=new Set() as A, v: V, k?:K) => {
  (acc as Set<V>).add(v);
  return acc as Set<V>;
};

/* test map and toSet by themselves */
// test correct - mapNum is Set<string> 
const mapStr = map((v: number) => `${v}`)(toSet)(undefined,1,'a');
// test correct - mapNum is Set<number> 
const mapNum = map((v: number) => v + 2)(toSet)(undefined,1,'a');
// @ts-expect-error test correct - string 'aa' passed to number mapper should error
const mapStrError = map((v: number) => v + 2)(toSet)(undefined,'aa','a');

/* transduce */
const transduce = <AccIn,AccOut,VIn,VOut,KIn,KOut>(
  collection: Map<KIn, VIn>,
  transducer:  <
                NextReducer extends (a:any,v:any,k?:any)=>any
              >(nextReducer:NextReducer)=>((a:AccIn,v:VIn,k?:KIn)=>AccOut),
  finalReducer: (a:AccOut|undefined,v:VOut,k?:KOut)=>AccOut,
) => {
  let combinedReducer = transducer(finalReducer);
  let acc = undefined as AccOut;
  for (const [key, value] of collection) {
    acc = combinedReducer(acc as unknown as AccIn, value, key);
  }
  return acc;
}

/* test transduce */
// @ts-expect-error correct - string collection passed to number mapper should error
const transduceStr = transduce(new Map([['a', 'aa']]), map((v: number) => v * 2), toSet);

// incorrect - transduceNum is unknown. Should be Set<number> like mapNum
const transduceNum = transduce(new Map([['a', 1]]), map((v: number) => v * 2), toSet);

现有测试情况

  • 单独使用map和toSet时类型推断完全正确:
    • mapStr被正确推断为Set<string>
    • mapNum被正确推断为Set<number>
    • 传入类型不匹配的参数时,TypeScript能正确报错(如mapStrError的@ts-expect-error验证)
  • 使用transduce时:
    • 类型不匹配的错误提示正常生效(如transduceStr的报错)
    • transduceNum的类型被错误推断为unknown,不符合预期(应该是Set<number>)

需求

修正transduce函数的类型定义,解决输出类型推断错误的问题,同时保留现有的错误提示能力。

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 00:45:58