【问题标题】:Property is incompatible with index signature属性与索引签名不兼容
【发布时间】:2020-07-10 10:09:55
【问题描述】:
const test = [
    {
        "a": 1
    },
    {
        "b": 1
    }
]
interface t {
    [key: string]: number
}
const ttt: t[] = test

属性“b”与索引签名不兼容。 类型“未定义”不可分配给类型“数字”。 如果我将密钥重命名为 b 或两个相同的密钥,它就可以工作。

【问题讨论】:

  • 去掉类型注解。

标签: typescript


【解决方案1】:

因为test 没有类型,所以被推断为这种类型:

({ a: number; b?: undefined; } | { b: number; a?: undefined; })[]

然后将test 分配给ttt,但在新接口t 中有可能未定义的b 键是不兼容的。

您可以通过将类型直接添加到 test 来解决此问题:

const test: t[] = [
    {
        "a": 1
    },
    {
        "b": 1
    }
]

【讨论】:

  • 感谢您的澄清。另一个问题是支持从“data.json”的其他部分导入测试导入测试。我们如何前进
  • 您只需要确保在创建test 变量的位置设置这样的类型。当您从另一个文件导入时,该类型将被保留。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2015-03-13
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 1970-01-01
相关资源
最近更新 更多