繁体   English   中英

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

[英]TypeScript error Element implicitly has an 'any' type because expression of type 'any' can't be used to index type

我收到此错误:

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

在这段代码中:

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>
  );
};

错误是当我使用 TypeScript 在CATEGORY_COLORS[item.category]CATEGORY_LABELS[item.category]上进行 hover 时。 我该如何解决?

当在 Typescript(例如 CATEGORY_LABELS)中定义原始 object 时 - 它不允许索引访问(例如 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',
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM