[英]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.