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

如何使用ReturnType<T>从多类型返回函数中提取单个类型

如何从ReturnType中提取特定属性的类型

你可以通过索引访问类型直接提取ReturnType<typeof Hoge>返回对象中A或B的类型,具体实现如下:

示例代码

首先定义原函数:

function Hoge() {
  // 示例复杂对象
  const A = { name: "foo", age: 123 };
  const B = { id: 456, active: true };
  return { A, B };
}

提取A或B的类型:

// 获取返回值中A属性的类型
type HogeA = ReturnType<typeof Hoge>['A'];
// 获取返回值中B属性的类型
type HogeB = ReturnType<typeof Hoge>['B'];

// 使用示例
const targetA: HogeA = { name: "bar", age: 456 }; // 类型匹配
const targetB: HogeB = { id: 789, active: false }; // 类型匹配

原理说明

ReturnType<typeof Hoge>会解析出函数Hoge的返回值类型(即包含A和B的对象类型),通过['A']或['B']的索引访问语法,可以直接获取对应属性的具体类型。

如果需要更灵活的属性提取(比如多个属性),也可以结合Pick工具类型:

// 提取单个属性A的类型,效果与索引访问一致
type HogeA = Pick<ReturnType<typeof Hoge>, 'A'>['A'];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:45:54