簡體   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