如何自动将TypeScript含数组字段的类型转为含Record字段的类型?
将数组字段的TypeScript类型转换为索引记录类型
问题背景
现有如下TypeScript类型,其中每个可选字段都是包含id: string属性的类型数组:
type AudioType = { id: string; url: string }; type AlbumType = { id: string; title: string }; type UserType = { id: string; username: string }; type VideoType = { id: string; duration: number }; type ApiResponse = { audios?: AudioType[]; albums?: AlbumType[]; users?: UserType[]; videos?: VideoType[]; }
需要自动将其转换为每个字段对应类型的索引记录类型,最终目标类型如下:
type IndexedResponse = { audios?: Record<string, AudioType>; albums?: Record<string, AlbumType>; users?: Record<string, UserType>; videos?: Record<string, VideoType>; }
解决方案
通过映射类型+类型推断就能实现这个转换,定义一个通用工具类型即可:
// 通用工具类型:将对象的数组字段转换为对应类型的Record索引 type ArrayToRecord<T> = { [K in keyof T]: T[K] extends (infer U)[] ? Record<string, U> : T[K]; }; // 应用到ApiResponse上,自动生成目标类型 type IndexedResponse = ArrayToRecord<ApiResponse>;
代码说明
[K in keyof T]:遍历原类型T的所有键名T[K] extends (infer U)[]:判断当前字段是否为数组类型,同时用infer U提取数组的元素类型URecord<string, U>:把提取到的元素类型U转换成以字符串为键的索引记录类型- 自动保留可选性:原类型
ApiResponse的字段自带?可选标记,映射类型会直接继承这个特性
效果验证
推导后的IndexedResponse会完全匹配目标类型:
audios类型为Record<string, AudioType> | undefinedalbums类型为Record<string, AlbumType> | undefined- 其余字段同理完成对应转换
内容的提问来源于stack exchange,提问作者Klein Maximus
相关产品推荐
相关产品推荐

