首页 > 解决方案 > 打字稿错误:TS7053 元素隐式具有“任何”类型

问题描述

这是我的代码的一部分:

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

myObj[propname] = 'string'

但我得到了错误:

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

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

标签: typescript

解决方案


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

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

推荐阅读