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
相关产品推荐
相关产品推荐

