为什么 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}但这将再次完全摆脱类型检查。
const foo = {
bar: 'bar'
};
for (const prop in foo) {
console.log(foo[prop]);
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,for..inTS 中的循环只会遍历字符串,而不是遍历keyof obj.
在这里,由于prop它只是一个string,而不是'bar',因此不能用于查找对象。
由于看起来您实际上并不关心键,只关心值,因此直接迭代值:
for (const val of Object.values(foo)) {
console.log(val);
}
Run Code Online (Sandbox Code Playgroud)
如果要一起迭代一个键及其关联的值,请使用Object.entries:
for (const [key, val] of Object.entries(foo)) {
console.log(key, val);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |