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

Angular 11 动态访问对象属性报错,如何正确提取指定属性生成目标数组

报错原因

TypeScript不允许用不确定是否属于对象合法键的类型去索引已知类型的对象:

  • 当你将遍历参数l设为any类型时,严格模式下会触发隐式any的校验报错
  • 当你将l设为string类型时,由于你的CustomObject没有声明通用的string索引签名,TS无法保证任意字符串都是该对象的合法键,因此报错

正确实现方案

方案1:用keyof限定标签数组的类型

直接将labels数组的元素类型限定为CustomObject的合法键,从源头上保证索引的合法性:

// 写法1:限定为CustomObject的所有合法键
const labels: Array<keyof CustomObject> = ['prop1', 'prop2'];

// 写法2:如果只允许prop1/prop2,可进一步缩小类型范围
// const labels: Array<'prop1' | 'prop2'> = ['prop1', 'prop2'];

labels.forEach(l => {
  this.myArray.push({ label: l, value: this.myObject[l] })
})

方案2:用as const自动推导字面量类型

不想手动写类型的话,可以用const断言让TS自动把数组元素推导为具体的字符串字面量类型,而非宽泛的string类型:

const labels = ['prop1', 'prop2'] as const;

labels.forEach(l => {
  this.myArray.push({ label: l, value: this.myObject[l] })
})

临时兼容方案

如果只是需要快速绕开校验,可以在索引时加类型断言,不推荐作为首选方案:

const labels = ['prop1', 'prop2'];
labels.forEach((l: string) => {
  this.myArray.push({ label: l, value: this.myObject[l as keyof CustomObject] })
})

注意:如果prop1/prop2的值本身不是number类型,需要自行添加类型转换或断言,保证最终myArray的类型符合{label: string, value: number}的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:51:01