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

如何在TypeScript中通过泛型生成任意函数的异步版本类型?

TypeScript 异步函数包装泛型实现方案

该需求完全可以实现,借助TypeScript内置的条件类型与infer类型推断关键字,就可以在不感知具体函数结构的前提下,自动提取参数列表与返回值,生成对应的异步函数类型。

基础泛型实现

type AsyncWrapper<T extends (...args: any[]) => any> = 
  T extends (...args: infer Args) => infer R 
    ? (...args: Args) => Promise<R> 
    : never;

实现逻辑说明

  • 首先对泛型参数T添加类型约束,仅允许传入函数类型,传入非函数类型时返回never做类型兜底
  • 通过infer Args自动提取原函数的完整参数类型元组,参数顺序、可选性、剩余参数、参数标签等所有属性会完全保留
  • 通过infer R自动提取原函数的返回值类型,外层包裹Promise作为异步函数的返回值

效果验证

使用问题中给出的示例测试,自动生成的类型与手动定义的异步类型完全等价:

// 原普通函数类型
type MyFunction = (x: number) => void;
// 自动生成异步版本,等价于 (x: number) => Promise<void>
type AsyncMyFunction = AsyncWrapper<MyFunction>;

// 类型校验通过
const demo: AsyncMyFunction = async (x) => {
  console.log(x);
};

该泛型支持所有合法函数类型的转换,包括多参数、可选参数、剩余参数、复杂返回值的场景:

// 复杂函数示例
type ComplexFunc = (a: string, b?: number, ...rest: boolean[]) => { id: number; name: string };
// 转换后类型:(a: string, b?: number, ...rest: boolean[]) => Promise<{ id: number; name: string }>
type AsyncComplexFunc = AsyncWrapper<ComplexFunc>;

优化:避免嵌套Promise

如果原函数本身已经返回Promise类型,基础实现会生成Promise<Promise<T>>的嵌套结构,如果需要自动展平嵌套Promise,可以结合TypeScript内置的Awaited工具类型调整实现:

type AsyncWrapper<T extends (...args: any[]) => any> = 
  T extends (...args: infer Args) => infer R 
    ? (...args: Args) => Promise<Awaited<R>> 
    : never;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 00:06:25