【问题标题】:How to fix this type inference in Typescript如何在 Typescript 中修复这种类型推断
【发布时间】:2019-12-16 14:51:01
【问题描述】:

const data = {
    "a": "111",
    "b": "222"
}

for (let key in data){
    console.log(data[key]); // TypeScript error here
}

错误:

元素隐含地具有“任何”类型,因为类型的表达式 'string' 不能用于索引类型 '{ "a": string; “b”:字符串; }'。 在类型上找不到带有“字符串”类型参数的索引签名 '{ "a": 字符串; “b”:字符串; }'。

【问题讨论】:

  • 我刚试过这段代码运行良好。你怎么会出现这个错误?
  • 看起来你的代码 sn-p 也可以。
  • @Train 试过了吗?这并不是一个真正的“错误”,它是一种类型不匹配,只有在特定情况下在打字稿环境中运行它时才会发生。
  • @Train 它肯定会创建一个打字稿类型错误typescriptlang.org/play/#code/…
  • @KevinB 好的,我明白了。我在 TS fiddle 中试过,效果很好。

标签: typescript


【解决方案1】:

你需要给data添加一个索引签名,即:

const data: { [key: string]: string } = {
    a: '111',
    b: '222'
}

【讨论】:

    【解决方案2】:

    你可以:

    console.log(data[key as keyof typeof data]);
    

    这很丑。

    但您似乎将data 视为具有字符串键的字典,而不是具有特定类型的特定属性。在哪个类型的datastring 索引能够使用任意字符串对其进行索引。

    let data: { [key: string]: string } = { a: '111', b: '222' }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-04
      • 2021-04-28
      • 2022-06-12
      • 2018-07-03
      • 2020-02-20
      • 2020-10-11
      • 2018-10-28
      • 2017-01-26
      相关资源
      最近更新 更多