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

Typescript如何给需成对重复传参的函数做动态类型定义

解决方案

可以借助 TypeScript 的递归可变元组类型实现,既不需要封装对象,也不受重载数量限制,编译期即可自动校验参数个数是否为偶数,奇数个参数会直接抛出类型错误。

完整实现代码

// 定义每一组参数的类型,此处按你的示例为 [string, number],可按需调整
type ParamPair = [a: string, b: number]

// 递归生成任意长度的成对参数元组,总长度永远为偶数
type AllowedParams = ParamPair | [...ParamPair, ...AllowedParams]

function myFunction(...params: AllowedParams) {
  // 可选:运行时参数校验,适配非TS环境调用场景
  if (params.length % 2 !== 0) {
    throw new Error('参数个数必须为偶数')
  }

  // 业务逻辑示例:按对遍历参数
  for (let i = 0; i < params.length; i += 2) {
    const paramA = params[i]
    const paramB = params[i + 1]
    // 处理逻辑...
  }
}

效果验证

  • 合法调用自动通过类型校验:
myFunction('test1', 1)
myFunction('test1', 1, 'test2', 2)
myFunction('test1', 1, 'test2', 2, 'test3', 3)
// 支持任意多组成对参数
  • 奇数个参数调用直接触发类型错误:
// 类型报错:类型 "[string, number, string]" 的参数不能赋给类型 "AllowedParams" 的参数
myFunction('test1', 1, 'test2')

方案优势

  • 无参数数量上限,支持任意多组成对参数传入
  • 编译期自动校验参数个数奇偶性,符合类型安全要求
  • 保持参数平铺写法,不需要额外封装对象
  • 扩展性强,只需修改ParamPair的定义即可调整每对参数的类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:09:03