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

TypeScript中将对象数组转为单个对象并保留值类型的实现方法

TypeScript 数组转键值对象保留完整类型方案

你原来的代码丢失类型信息的核心原因有两个:

  • 输入类型固定了name为string、value为any,无法推导具体的键名和值类型
  • 普通声明的数组会被TS自动拓宽字面量类型,name的具体字符串值会被抹除

完整实现代码

// 单个输入项的泛型类型约束
type InputItem<K extends string, V> = { name: K, value: V }

// 将输入数组类型映射为输出对象类型
type MapInputToOutput<T extends InputItem<string, any>[]> = {
  [Item in T[number] as Item['name']]: Item['value']
}

// 泛型转换函数,自动推导输入类型并返回映射后的精准类型
function convertArrayToObject<T extends InputItem<string, any>[]>(input: [...T]): MapInputToOutput<T> {
  return input.reduce((output, record) => ({
    ...output,
    [record.name]: record.value
  }), {} as MapInputToOutput<T>)
}

// 输入数组加as const断言,保留字面量类型不被拓宽
const input = [
  { name: 'name', value: 'Michal' },
  { name: 'age', value: 24 },
  { name: 'numbers', value: [4, 7, 9] }
] as const

const output = convertArrayToObject(input)

类型校验效果验证

  • output.age.length:TS直接报错,提示number类型不存在length属性,符合预期
  • output.numbers.length:TS能正确识别numbers为readonly [4, 7, 9]类型,length值为3,无报错
  • output.address:TS报错提示属性不存在,符合预期

如果不需要数组为只读类型,也可以用satisfies关键字约束输入格式的同时保留原始类型,效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:09:05