TypeScript 错误元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型

Ali*_*ien 0 typescript reactjs

我收到此错误:

  Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ foo: string; bar: string; }'.ts(7053)
Run Code Online (Sandbox Code Playgroud)

在此代码中:

const CATEGORY_COLORS = {
  foo: '#6f79F6',
  bar: '#4fA0E9',
};

const CATEGORY_LABELS = {
  foo: 'FOO',
  bar: 'BAR',
};

const ItemRenderer = ({ item }: ItemRendererPropsType): React.ReactElement => {
  return (
    <div>
      <Tag color={CATEGORY_COLORS[item.category]}>
        {CATEGORY_LABELS[item.category]}
      </Tag>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

CATEGORY_COLORS[item.category]当我将鼠标悬停在 TypeScript或上时会出现错误CATEGORY_LABELS[item.category]。我该如何解决?

小智 6

当在 Typescript 中定义原始对象(例如 CATEGORY_LABELS)时,它将不允许索引访问(例如 CATEGORY_LABELS[key]),其中 key 是字符串。在您的示例中,我假设其item.category类型为string.

要么item.category应该是类型keyof typeof CATEGORY_LABELS,要么需要重新定义 CATEGORY_LABELS 以允许通过随机字符串进行索引,但这不太安全,因为您不能保证传入有效的密钥。

const CATEGORY_LABELS: Record<string, string> = {
  foo: 'FOO',
  bar: 'BAR',
};
Run Code Online (Sandbox Code Playgroud)