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

如何让TypeScript泛型函数同时支持数组参数与剩余参数调用?

解决TypeScript泛型函数同时支持剩余参数和数组参数的问题

方法一:使用函数重载

通过定义多个重载签名,让函数同时支持数组参数和剩余参数的调用方式,且保证两种调用都返回Something<T>类型:

// 示例定义Something类型
type Something<T> = { items: T[] };

// 重载签名1:接受数组参数
function fn<T>(args: T[]): Something<T>;
// 重载签名2:接受剩余参数
function fn<T>(...args: T[]): Something<T>;
// 函数实现逻辑
function fn<T>(...args: [T[]] | T[]): Something<T> {
  // 统一处理参数:如果传入单个数组则取该数组,否则直接用剩余参数
  const targetArgs = Array.isArray(args[0]) ? args[0] : args as T[];
  // 替换为你的原函数逻辑
  return { items: targetArgs } as Something<T>;
}

// 测试调用,两种方式均返回Something<number>
const something1 = fn(1, 2, 3, 4);
const something2 = fn([1, 2, 3, 4]);

方法二:单一签名结合泛型约束

通过泛型约束让参数兼容T[]或T的剩余参数,同时推导正确的返回类型:

type Something<T> = { items: T[] };

function fn<T>(args: T[] | [...T[]]): Something<T> {
  const targetArgs = Array.isArray(args) ? args : [args];
  // 替换为你的原函数逻辑
  return { items: targetArgs } as Something<T>;
}

// 测试调用
const something1 = fn(1, 2, 3, 4); // Something<number>
const something2 = fn([1, 2, 3, 4]); // Something<number>

两种方法都能满足需求:函数重载写法更直观,TypeScript类型推导精度更高;单一签名写法更简洁,适合逻辑简单的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:20:03