Typescript 元素隐式具有类型 any 和 for...in 循环 [英] Typescript element implicitly has type any with for...in loops

查看:84
本文介绍了Typescript 元素隐式具有类型 any 和 for...in 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 JSON 文件导入的 JSON 对象(使用 resolveJsonModule: true).该对象如下所示:

I have a JSON object imported from a JSON file (with resolveJsonModule: true). The object looks like this:

"myobject": {
  "prop1": "foo",
  "prop2": "bar"
}

因此它的类型如下所示:

and it's type therefore looks like this:

myobject: { prop1: string, prop2: string }

这很好,但是当我尝试使用 for...in 循环时,

That's very nice but when I try to use a for...in loop,

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; }'.

我知道这意味着迭代器 keystring 类型而不是 'prop1' 类型 |'prop2'.但我不明白为什么迭代器没有得到这种类型,因为我显式地遍历了 myobject 的属性名称.我是否错过了启用此行为的 tsconfig 属性?我不想这样做:

I understand that this means the iterator key is of type string and not of type 'prop1' | 'prop2'. But I don't understand why the iterator doesn't get this type because I'm explicitly iterating through the property names of myobject. Did I miss a tsconfig property that enables this behavior? I would like not to do this:

for (const key in myobject)  {
  console.log(myobject[key as 'prop1' | 'prop2'])
}

因为:

  1. 我将来可能会添加新的属性;和
  2. 这似乎有点作弊,我觉得有更好的方法来做到这一点.

推荐答案

更好的方法是:

for (const key in myobject)  {
  console.log(myobject[key as keyof typeof myobject])
}

这样,添加属性或重命名时不会中断

In this way, it won't break when you add a property or rename it

这篇关于Typescript 元素隐式具有类型 any 和 for...in 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆