我有一个从 JSON 文件(带有resolveJsonModule: true
)导入的 JSON 对象。该对象如下所示:
"myobject": {
"prop1": "foo",
"prop2": "bar"
}
它的类型因此看起来像这样:
myobject: { prop1: string, prop2: string }
这很好,但是当我尝试使用for...in
循环时,
for (const key in myobject) {
console.log(myobject[key])
}
我收到此错误:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ "prop1": string; "prop2": string; }'.
No index signature with a parameter of type 'string' was found on type '{ "prop1": string; "prop2": string; }'.
我知道这意味着迭代器key
是 typestring
而不是 type 'prop1' | 'prop2'
。但我不明白为什么迭代器没有得到这种类型,因为我明确地迭代了myobject
. 我是否错过了启用此行为的 tsconfig 属性?我不想这样做:
for (const key in myobject) {
console.log(myobject[key as 'prop1' | 'prop2'])
}
因为:
- 我将来可能会添加新的属性;和
- 这似乎有点作弊,我觉得有更好的方法来做到这一点。