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

TypeScript中解决回调函数参数类型变为联合类型的方法

解决TypeScript回调函数参数类型推断问题

你的问题核心是TypeScript默认会把数组字面量拓宽为联合类型数组,而非精确的元组类型,导致回调参数被推断为number | boolean。以下是几种可行的解决方法:

方法1:使用const断言约束数组类型

在传入的数组字面量后添加as const,强制TypeScript将其推断为只读元组,回调的参数类型会自动匹配元组的各个元素类型:

const func = <Args extends any[]>(args: Args, callback: (...args: Args) => void) => callback(...args);

func([1, true] as const, (a0, a1) => {
  console.log(a0, a1); // a0类型为1(字面量类型),a1类型为true(字面量类型)
});

如果不需要字面量类型,仅需number和boolean,这种方式也能满足精确类型推断的需求,后续可根据业务场景调整。

方法2:调整泛型约束为只读元组

修改函数的泛型约束,让Args继承自readonly any[],TypeScript会自动将数组字面量推断为元组而非联合数组:

const func = <Args extends readonly any[]>(args: Args, callback: (...args: Args) => void) => callback(...args);

func([1, true], (a0, a1) => {
  console.log(a0, a1); // a0类型为number,a1类型为boolean
});

方法3:显式指定泛型参数

调用func时直接指定泛型为目标元组类型,强制约束参数和回调的类型:

const func = <Args extends any[]>(args: Args, callback: (...args: Args) => void) => callback(...args);

func<[number, boolean]>([1, true], (a0, a1) => {
  console.log(a0, a1); // a0类型为number,a1类型为boolean
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:43:33