typescript 打字稿错误:TS7053 元素隐式具有“任何”类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56833469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:50:15  来源:igfitidea点击:

Typescript error: TS7053 Element implicitly has an 'any' type

typescript

提问by Cichy

this is part of my code:

这是我的代码的一部分:

const myObj: object = {}
const propname = 'propname'

myObj[propname] = 'string'

but I got error:

但我有错误:

ERROR in path/to/file.ts(4,1)
TS7053: Element implicitly has an 'any' type because expression of type '"propname"' can't be used to index type '{}'.
  Property 'propname' does not exist on type '{}'.

What is wrong here, and how can I fix it?

这里有什么问题,我该如何解决?

回答by Murat Karag?z

You have to define what kind of index type the object has. In your case it is a stringbased index.

您必须定义对象具有的索引类型。在您的情况下,它是一个string基于索引。

const myObj: {[index: string]:any} = {}

回答by Ivan Paniagua

Why just simple replace 'object' with 'any':

为什么只是简单地用“任何”替换“对象”:

const myObj: any = {}
const propname = 'propname'

myObj[propname] = 'string'

Another short alternative.

另一个简短的选择。