【问题标题】:Typescript error: TS7053 Element implicitly has an 'any' type打字稿错误:TS7053 元素隐式具有“任何”类型
【发布时间】:2019-11-11 23:31:40
【问题描述】:

这是我的代码的一部分:

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


【解决方案1】:

请先创建 TS Map。

const myObj = new Map();
myObj.set('propname', "something");

const propname = 'propname'
myObj.get(propname)

【讨论】:

    【解决方案2】:

    为什么只是简单地将 'object' 替换为 'any':

    const myObj: any = {}
    const propname = 'propname'
    
    myObj[propname] = 'string'
    

    另一个简短的选择。

    【讨论】:

    • 那为什么要使用 Typescript?
    • @RamoFX 显然是为了仪式 :)
    • 类型注释:any 是我所缺少的。这在 TS 中处理 JS 对象时很有用,例如传递给JSON.stringify(...)
    • @imallett 将某些东西注释为any 摆脱了所有类型安全,完全违背了使用 Typescript 的目的。努力正确注释类型,以便 TS 可以帮助您提前发现错误。
    • @theberzi 正如我在评论中所建议的,一些 TS API 不是类型安全的:P
    【解决方案3】:

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

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

    【讨论】:

    • 很好的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2018-11-30
    • 2021-12-13
    • 2021-03-29
    • 2021-11-17
    • 2021-04-23
    相关资源
    最近更新 更多