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

如何从TypeScript的Record中提取值类型?

从Record返回类型中提取值类型的解决方案

你可以通过索引访问类型结合ReturnType工具类型,从函数的Record返回类型中提取值类型,具体实现如下:

通用工具类型定义

先定义一个可复用的工具类型,用来提取Record类型的值类型:

type ExtractedValueOf<T extends Record<string, any>> = T[string];

针对你的示例修改

在你的场景中,无需直接引用SomeType,可以通过ReturnType<typeof sample>拿到sample函数的返回类型,再用上述工具类型提取值类型:

type SomeType = {
  field: string;
  another: string;
};

function sample(): Record<string, SomeType> {
  return {
    object: {
      field: "Hello",
      another: "World",
    },
  };
}

function myFunction() {
  return myOtherFunction(sample().object);
}

// 直接提取sample返回类型中的值类型作为参数类型
function myOtherFunction(sampleObject: ExtractedValueOf<ReturnType<typeof sample>>) {
  // 逻辑处理
  return sampleObject;
}

简化写法(无需工具类型)

如果不需要复用工具类型,也可以直接写:

function myOtherFunction(sampleObject: ReturnType<typeof sample>[string]) {
  // 逻辑处理
  return sampleObject;
}

为什么你的尝试不生效

你之前写的ReturnType<keyof ReturnType>逻辑有误:keyof ReturnType<typeof sample>得到的是string类型(Record的键类型),而ReturnType只能作用于函数类型,所以这种写法不符合TypeScript的类型规则,自然无法得到预期的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:42:53