打字稿错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

时间:2021-01-18 21:27:36

标签: typescript types typeerror react-intl

尝试根据 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'

1 个答案:

答案 0 :(得分:2)

你需要添加一个显式类型断言来解决这个问题:

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