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

如何编写泛型类型映射对象各函数键的返回类型?

实现映射函数返回类型的泛型MapReturnType

先看示例场景:

type T1 = {
  a: () => string,
  b: () => number
}

type T2 = {
  [P in keyof T1]: ReturnType<T1[P]>
}

此时T2的类型等价于:

{
  a: string,
  b: number
}

要编写通用的泛型MapReturnType,让它能接收所有键均为函数的对象类型,并将每个键的类型映射为对应函数的返回类型,只需要在泛型约束中限定T的每个属性都是函数类型即可:

type MapReturnType<T extends Record<string, (...args: any[]) => any>> = {
  [P in keyof T]: ReturnType<T[P]>
}

补充说明:

  • Record<string, (...args: any[]) => any> 用来约束泛型参数T必须是对象类型,且所有属性值都是支持任意参数、任意返回值的函数类型,这样ReturnType<T[P]>才能合法获取每个属性函数的返回类型。
  • 如果需要兼容对象键为number或symbol的场景,可以把约束改成T extends Record<PropertyKey, (...args: any[]) => any>——PropertyKey是TypeScript内置类型,代表string | number | symbol,即对象键的合法类型范围。

测试示例:

type TestType = {
  foo: () => boolean,
  bar: (id: number) => { name: string }
}

type TestResult = MapReturnType<TestType>
// TestResult 等价于 { foo: boolean; bar: { name: string } }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:14:58