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

如何用一行代码基于数组元素创建TypeScript Record对象

一行TypeScript实现方案

当然可以用一行代码搞定,给你两种常用的简洁写法:

方法1:使用Object.fromEntries(推荐)

这种方式最直观,把数组转成键值对数组后直接生成对象:

const required = ['firstName', 'lastName'];
const exist: Record<string, string[]> = Object.fromEntries(required.map(key => [key, []]));

如果想要更严谨的类型(让exist的键只能是数组里的具体值,而非宽泛的string),可以给数组加上as const断言:

const required = ['firstName', 'lastName'] as const;
const exist: Record<typeof required[number], string[]> = Object.fromEntries(required.map(key => [key, []]));

此时exist的类型会被推断为{ firstName: string[]; lastName: string[] },更符合TypeScript的类型安全要求。

方法2:使用reduce

通过累加器逐步构建对象:

const required = ['firstName', 'lastName'];
const exist: Record<string, string[]> = required.reduce((obj, key) => ({ ...obj, [key]: [] }), {});

另外提一句,你原代码里的this.exist应该是笔误,因为exist是局部变量,直接写exist[key] = []就好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:15:40