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

如何通过TypeScript泛型让传递函数的参数自动匹配指定类型?

问题原因及解决方案

为什么res类型是any?

你定义的resHandler是独立函数,它的参数res没有显式声明类型,而且TypeScript不会从函数被调用的上下文反向推断独立函数的参数类型。虽然调用sendRequest时指定了泛型PersonType,但resHandler本身的类型和这个调用上下文是分离的,TypeScript无法自动把PersonType关联到resHandler的参数上,所以res会被默认推断为any。

解决方法

方法1:给resHandler参数显式指定类型

直接给res加上PersonType类型声明,TypeScript就能识别它的类型:

function resHandler(res: PersonType) {
  console.log(res) // res类型为PersonType
}

方法2:在调用时传入匿名函数(或箭头函数)

把处理逻辑直接写在sendRequest的调用参数里,TypeScript会根据泛型参数PersonType自动推断出参数类型:

sendRequest<PersonType>((res) => {
  console.log(res) // res自动推断为PersonType
})

方法3:让resHandler关联泛型类型(进阶用法)

如果需要复用resHandler处理不同类型的响应,可以把它定义成泛型函数:

function resHandler<T>(res: T) {
  console.log(res)
}
// 调用时显式指定泛型
sendRequest<PersonType>(resHandler<PersonType>)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:15:03