You need to enable JavaScript to run this app. TypeScript如何从常量数组内联初始化对应类型的对象属性
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何从常量数组内联初始化对应类型的对象属性

前置修正

你定义的类型T存在语法错误,多了一层多余的左大括号,正确的类型定义如下:

type T = { [key in typeof a[number]]: number };
报错原因
  • a.map((prop) => [prop, 0])执行后返回的是二维数组[['one', 0], ['two', 0]],而你定义的类型T是包含one、two属性的对象类型,二者类型完全不匹配,因此触发类型报错。
正确实现方案

方案1:使用Object.fromEntries转换

写法最简洁,把map返回的键值对数组传入Object.fromEntries转换为对象,配合类型断言即可符合类型要求:

const a = ['one', 'two'] as const;
type T = { [key in typeof a[number]]: number };

const z: T = Object.fromEntries(a.map(prop => [prop, 0])) as T;

方案2:使用Array.reduce构建对象

通过reduce遍历数组直接构建目标对象,初始化时指定累加器类型即可,不需要额外转换:

const a = ['one', 'two'] as const;
type T = { [key in typeof a[number]]: number };

const z = a.reduce((acc, curr) => {
  acc[curr] = 0;
  return acc;
}, {} as T);

两种方案最终生成的z都符合{one: 0, two: 0}的预期结构,可正常通过TS类型校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 18:42:04