[英]TypeScript error Element implicitly has an 'any' type because expression of type 'any' can't be used to index type
I am getting this error:我收到此错误:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ foo: string; bar: string; }'.ts(7053)
In this code:在这段代码中:
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>
);
};
The error is when I hover over either CATEGORY_COLORS[item.category]
or CATEGORY_LABELS[item.category]
with TypeScript.错误是当我使用 TypeScript 在
CATEGORY_COLORS[item.category]
或CATEGORY_LABELS[item.category]
上进行 hover 时。 How do I resolve?我该如何解决?
When a raw object is defined in Typescript (eg CATEGORY_LABELS) - it won't allow for indexed access (eg CATEGORY_LABELS[key]) where key is a string.当在 Typescript(例如 CATEGORY_LABELS)中定义原始 object 时 - 它不允许索引访问(例如 CATEGORY_LABELS[key]),其中 key 是字符串。 In your example, I assume that
item.category
is of type string
.在您的示例中,我假设
item.category
的类型为string
。
Either item.category
should be of type keyof typeof CATEGORY_LABELS
or you need to redefine CATEGORY_LABELS to allow for indexing by a random string, but that is less typesafe, since you aren't guaranteeing that you will pass in a valid key. 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.