![](/img/trans.png)
[英]Element implicitly has an 'any' type because expression of type 'string' can't be used to index type - TypeScript Error
[英]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.