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

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

正在尝试根据 feature 名称获取模式的一些数据。 该特征本身是一个来自 API 的字符串。 messages 对象用于翻译其他国家/地区的字符串。

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 函数中遇到 2 个打字稿错误,特别是在我使用串联字符串键获取消息的位中:

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 来引用对象中的键。

然而,Typescript 4.1 添加了对模板文字类型的支持,因此如果您能够升级您的环境以使用它,则可能不再需要它。

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