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

如何在TypeScript中根据参数索引奇偶性限制函数参数类型?

实现按索引奇偶性约束参数类型的flow函数

需求是实现一个支持任意数量参数的flow函数,参数类型严格按索引奇偶性区分:

  • 偶数索引(从0开始)的参数必须是() => boolean类型的函数
  • 奇数索引的参数必须是'and' | 'or' | 'then'字面量类型

示例调用:flow(isMachineReady(), 'and', isWaterHot(), 'or', isMilkHot(), 'then', serveCoffee()),当传入不符合类型要求的参数(比如第二个参数传isWaterHot())时,TypeScript要报错。你之前用FlowArgCouple数组的写法无法生效,因为它限制了参数必须是完整的操作数-操作符对,没法处理结尾的单个操作数,且索引约束不精准。

解决方案

用递归条件类型定义参数列表,确保每一组都是「操作数 + 操作符」,最后可以追加一个操作数:

// 定义递归的参数类型,严格匹配索引奇偶性要求
type FlowArgs = 
  | [operand: () => boolean]
  | [operand: () => boolean, operator: 'and' | 'or' | 'then', ...rest: FlowArgs];

function flow(...args: FlowArgs) {
  // 这里写函数逻辑,示例实现供参考
  let result = true;
  for (let i = 0; i < args.length; i += 2) {
    const operand = args[i] as () => boolean;
    const currentVal = operand();
    if (i === 0) {
      result = currentVal;
    } else {
      const operator = args[i-1] as 'and' | 'or' | 'then';
      switch (operator) {
        case 'and':
          result = result && currentVal;
          break;
        case 'or':
          result = result || currentVal;
          break;
        case 'then':
          result = currentVal; // then逻辑直接覆盖之前结果
          break;
      }
    }
  }
  return result;
}

// 测试正确调用(无类型错误)
const isMachineReady = () => true;
const isWaterHot = () => true;
const isMilkHot = () => false;
const serveCoffee = () => true;

flow(isMachineReady(), 'and', isWaterHot(), 'or', isMilkHot(), 'then', serveCoffee());

// 测试错误调用(TypeScript会抛出类型错误)
// flow(isMachineReady(), isWaterHot(), 'or', isMilkHot()); // 第二个参数不符合operator类型要求

为什么之前的写法失效

你之前定义的[...FlowArgCouple][]要求参数是多个FlowArgCouple([() => boolean, 操作符])的展开,这意味着参数总数必须是偶数,且每两个参数为一组。但实际需求允许参数总数为奇数(最后一个是单独的操作数),所以之前的类型无法匹配这种场景,导致类型约束失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:42:54