如何在TypeScript中提取Record类型的值类型?
解决方案
你可以通过TypeScript的索引访问类型直接从导出的MyRecordSet中提取其对应的值类型,无需访问未导出的MySecretComplexType。
具体实现示例
lib.ts 文件内容
// 未导出的内部类型 type MySecretComplexType = { id: number; name: string; details: { active: boolean; createdAt: Date; }; }; // 导出的基于内部类型的Record类型 export type MyRecordSet = Record<string, MySecretComplexType>;
myWorker.ts 文件内容
import type { MyRecordSet } from './lib'; // 通过索引访问类型 MyRecordSet[string] 获取对应的值类型 function myWorker(item: MyRecordSet[string]) { console.log(item.id, item.name, item.details.active); // TypeScript会自动推导item的类型为MySecretComplexType的结构,支持完整类型提示 }
原理说明
Record<K, T>类型的本质是键类型为K、值类型为T的对象类型。通过MyRecordSet[string]这种索引访问语法,TypeScript会自动解析出该Record类型对应的值类型——也就是未导出的MySecretComplexType。这种方式完全依赖TypeScript的类型系统推导,不需要额外定义类型或暴露内部实现。
内容的提问来源于stack exchange,提问作者MidnightLightning
相关产品推荐
相关产品推荐

