【问题标题】:Typescript complaining about explicit type not having index signature打字稿抱怨显式类型没有索引签名
【发布时间】:2019-05-23 22:22:40
【问题描述】:

Typescript 在以下代码中引发错误 "Element implicitly has an 'any' type because type 'HumansToDogs' has no index signature."

对我来说,一切似乎都是明确而直接的,有人可以帮忙吗?

type HumanName = 'Jessie' | 'Mark';
type DogName = 'Spot' | 'Buddy';

type HumansToDogs = {
  [key in HumanName]: DogName;  // Isn't this an index signature?
}

const humansToDogs: HumansToDogs = {
  'Jessie': 'Buddy',
  'Mark': 'Spot',
};

for (const human in humansToDogs) {
  const dog = humansToDogs[human];  // Index signature error here
}

【问题讨论】:

    标签: javascript typescript types typescript-typings


    【解决方案1】:

    for..of 将循环变量键入为string。使用noImplicitAny,您不能索引到具有任意string 的类型。最简单的解决方案是使用类型断言:

    for (const human  in humansToDogs) {
        const dog = humansToDogs[human as HumanName];  // Index signature error here
    }
    

    【讨论】:

      【解决方案2】:

      您可以显式地让 Typescript 编译器知道 human 引用 HumanName 的键,如下所示:

      humansToDogs[human as keyof HumanName]
      

      但更好的方法是定义数据的形状,您可以显式定义一个新类型,将索引声明为字符串:

      type HumanNames = {[k: string] HumanName};
      

      【讨论】:

        猜你喜欢
        • 2018-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 1970-01-01
        • 2021-03-06
        • 1970-01-01
        • 2021-05-20
        相关资源
        最近更新 更多