const data = {
"a": "111",
"b": "222"
}
for (let key in data){
console.log(data[key]); // TypeScript error here
}
错误:
元素隐式地具有“ any”类型,因为类型的表达式 'string'不能用于索引类型'{“ a”:string; “ b”:字符串; }'。 在类型上未找到带有“字符串”类型参数的索引签名 '{“ a”:字符串; “ b”:字符串; }'。
答案 0 :(得分:1)
您需要为data
添加索引签名,即:
const data: { [key: string]: string } = {
a: '111',
b: '222'
}
答案 1 :(得分:1)
您可以:
console.log(data[key as keyof typeof data]);
哪一个很丑。
但是似乎您正在将data
视为具有字符串键的字典,而不是具有特定类型的特定属性。带有索引data
的{{1}}类型可以使用任意字符串对其进行索引。
string