“forin”循环中TypeScript中“无索引签名”错误的原因
为什么 TypeScript 4.1.3 会抱怨循环中Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ bar: string; }'. No index signature with a parameter of type 'string' was found on type '{ bar: string; }'的 foo[prop] 访问for in根据定义处理引用对象的属性?
当然,我可以摆脱将对象声明为或类似的类型检查any,{[key: string]: any}但这将再次完全摆脱类型检查。
https://www.typescriptlang.org/play?ssl=7&ssc=2&pln=1&pc=1#code/MYewdgzgLgBAZiEMC8MDeAoG2YCMCGATgFwwDkBhZGAvgNwYYKEwAUoksADoSFzAEsw8RAEp0WHBwggANzVFAdh6hBwggANzVFAdh6
const foo = {
bar: 'bar'
};
for (const prop in foo) {
console.log(foo[prop]);
}
回答
出于某种原因,for..inTS 中的循环只会遍历字符串,而不是遍历keyof obj.
在这里,由于prop它只是一个string,而不是'bar',因此不能用于查找对象。
由于看起来您实际上并不关心键,只关心值,因此直接迭代值:
for (const val of Object.values(foo)) {
console.log(val);
}
如果要一起迭代一个键及其关联的值,请使用Object.entries:
for (const [key, val] of Object.entries(foo)) {
console.log(key, val);
}