繁体   English   中英

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

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

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
}

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

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

你可以明确地让打字稿编译器知道, human referes到的一个关键HumanName如下:

humansToDogs[human as keyof HumanName]

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

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

暂无
暂无

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

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