簡體   English   中英

Typescript 錯誤:元素隱式具有“任何”類型,因為“字符串”類型的表達式不能用於索引類型

[英]Typescript Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

嘗試根據feature名稱獲取模式的一些數據。 該功能本身是來自 API 的字符串。 messages object 用於翻譯其他國家的字符串。

import { defineMessages } from 'react-intl';

messages = defineMessages({
  userLimitsHeading: {
    defaultMessage: 'User limits',
  },
  userLimitsSubheading: {
    defaultMessage: 'Get the flexibility to grow your team beyond 10 users.',
  },
  agentLimitHeading: {
    defaultMessage: 'Agent limits',
  },
  agentLimitSubheading: {
    defaultMessage: 'Get the flexibility to grow your team beyond 3 agents.',
  },
});

interface ModernizedPlanSelectionModalTypes {
  feature: string;
}

const getData = (feature) => {
  const heading = messages[`${feature}Heading`];
  const subHeading = messages[`${feature}Subheading`];
  return {
    heading,
    subHeading,
  };
}

我在 getData function 中收到 2 個 typescript 錯誤,特別是在我使用連接字符串鍵獲取消息的位中:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'userLimitsHeading: { id: string; description: string; defaultMessage: string; }; userLimitsSubheading: { id: string; description: string; defaultMessage: string; }; ... //Continues on for the rest of them
No index signature with a parameter of type 'string' was found on type ' userLimitsHeading: { id: string; description: string; defaultMessage: string; }; userLimitsSubheading: { id: string; description: string; defaultMessage: string; }; //Continues on for the rest of them'

您需要添加一個顯式類型斷言來解決這個問題,如下所示:

const getData = (feature: string) => {
  const heading = messages[`${feature}Heading` as keyof typeof messages]
  const subHeading = messages[`${feature}Subheading` as keyof typeof messages]
  return {
    heading,
    subHeading,
  }
}

問題的根源是messages變量中的鍵鍵入為

'userLimitsHeading' | 'userLimitsSubheading' | 'agentLimitHeading' | 'agentLimitSubheading'

這是string的一個窄子集。

${feature}Heading被輸入到string - 錯誤消息告訴您不能使用任何string來引用 object 中的鍵。

Typescript 4.1 但是添加了對模板文字類型的支持,因此如果您能夠升級您的環境以使用它,則可能不再需要它。

另見https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM