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

如何优雅获取函数ReturnType返回值的属性类型?

TypeScript 直接获取函数返回值的属性类型

你可以直接通过 ReturnType<typeof 函数名>['属性名'] 的方式提取属性类型,无需创建未使用的中间变量,这是更规范简洁的实现方式:

const f = () => ({ a: 'a', b: 0 });
// 直接获取返回值中a的类型
type AType = ReturnType<typeof f>['a']; // 类型为 string
// 直接获取返回值中b的类型
type BType = ReturnType<typeof f>['b']; // 类型为 number

逻辑说明

ReturnType<typeof f> 会先推导函数 f 的返回值类型(即 {a: string; b: number}),再通过索引访问语法 ['a']/['b'] 直接提取对应属性的类型,完全避免了冗余变量的声明。

如果需要多次复用函数返回值类型,也可以先定义类型别名,提升代码可读性:

const f = () => ({ a: 'a', b: 0 });
// 预先定义返回值类型别名
type FReturnType = ReturnType<typeof f>;
// 基于别名提取属性类型
type AType = FReturnType['a'];
type BType = FReturnType['b'];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:39:51