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

TypeScript调用泛型函数时如何避免重复指定类型参数?

可以避免重复指定泛型类型参数

当然可以!你完全不用重复指定<number>和<string>类型参数——TypeScript的类型推断机制能帮你自动搞定这件事。

因为你的generic函数的泛型参数T是通过入参fn的返回值类型推导出来的:fn1的返回值明确是ActionResponse<number>,fn2是ActionResponse<string>,TypeScript会自动识别这些类型,进而推断出generic函数中T的具体类型,不需要你手动写出来。

修改后的代码如下:

interface Result<T> {
  data: T
}

type ActionResponse<T> = Result<T>;

function fn1(): ActionResponse<number> {
  return {
    data: 1,
  };
}

function fn2(): ActionResponse<string> {
  return {
    data: '1',
  };
}

function generic<T>(fn: () => ActionResponse<T>): T {
  const response = fn();
  return response.data;
}

// 去掉显式的类型参数,TS自动推断T的类型
const res1 = generic(fn1); // res1 类型为 number
const res2 = generic(fn2); // res2 类型为 string

这样写出来的代码更简洁,而且类型安全性完全不受影响——res1和res2的类型依然会被正确推断为number和string,和你手动指定类型参数的效果一模一样。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:03:10