简体   繁体   English

打字稿抱怨显式类型没有索引签名

[英]Typescript complaining about explicit type not having index signature

Typescript is raising the error "Element implicitly has an 'any' type because type 'HumansToDogs' has no index signature." Typescript 引发错误"Element implicitly has an 'any' type because type 'HumansToDogs' has no index signature." on the following code.在以下代码中。

Everything seems explicit and straightforward to me, can anyone help?对我来说一切都显得明确而直接,有人可以帮忙吗?

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
}

The for..of will type the loop variable as string . for..of将循环变量输入为string With noImplicitAny you can't index into a type with an arbitrary string .使用noImplicitAny您不能索引到具有任意string的类型。 The simplest solution is to use a type assertion:最简单的解决方案是使用类型断言:

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

You can explicitly let the Typescript compiler know that human referes to a key of HumanName as follows:你可以明确地让打字稿编译器知道, human referes到的一个关键HumanName如下:

humansToDogs[human as keyof HumanName]

But a better way is to define the shape of your data, you can explicitly define a new type that declares the index as a string:但更好的方法是定义数据的形状,您可以显式定义一个新类型,将索引声明为字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM