I'm quite new to TS and would like to understand why I get a type error in the following code (simplified):
我是TS的新手,我想知道为什么我在以下代码中遇到类型错误(简化):
"use client";
import { ArrowDownWideNarrow, Settings } from "lucide-react";
interface LinkItemProps {
name: string;
}
const iconMap = {
Categories: <ArrowDownWideNarrow />,
Admin: <Settings />,
};
export const LinkItem = ({ name }: LinkItemProps) => {
<div>
{iconMap[name]}
</div>
}
The error is in the `{iconMap[name]}:
错误在`{iconMap[名称]}中:
"Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Categories: Element; Admin: Element; }'.
“元素隐式具有‘any’类型,因为‘字符串’类型的表达式不能用于索引类型‘{Categories:Element;Admin:Element;}’。
No index signature with a parameter of type 'string' was found on type '{ Categories: Element; Admin: Element; }'."
在类型‘{Categories:Element;Admin:Element;}’上未找到参数类型为‘STRING’的索引签名。“
The parent element
has the following:
父元素具有以下内容:
const LINKS = [
{
href: "/admin",
name: "Admin",
id: "admin",
},
{
href: "/categories",
name: "Categories",
id: "categories",
},
];
export const Sidebar = async () => {
return (
<div>
{LINKS.map((link) => (
<div key={link.href}>
<LinkItem href={link.href} id={link.id} name={link.name} />
</div>
))}
</div>
)
}
更多回答
You can narrow the type of name
with interface LinkItemProps { name: keyof typeof iconMap }
to make it work.
您可以使用接口LinkItemProps{name:keyof typeof iconMap}缩小名称类型以使其工作。
优秀答案推荐
No index signature with a parameter of type 'string' was found on type '{ Categories: Element; Admin: Element; }'."
The string
type is too wide, you could be more specific on the name
prop type so it properly inherits the fields based on the iconMap
object.
字符串类型太宽,您可以更具体地说明名称道具类型,以便它正确地继承基于图标映射对象的字段。
Typescript demo
打字演示
interface LinkItemProps {
name: keyof typeof iconMap;
}
or a manual, strictly typed approach:
或者是一种手动、严格键入的方法:
interface LinkItemProps {
name: 'Categories' | 'Admin';
}
Updated typescript demo
更新的打字演示
更多回答
Thank you very much, kind user ;) But now I have an error in the parent element (I edited my question to include the parent). The error is there now saying: "Type 'string' is not assignable to type '"Categories" | "Admin"'." That's in property "name" in the LinkItem inside the map
. Thank you, I understand my question must be quite basic :)
非常感谢,善良的用户;)但现在我在父元素中有一个错误(我编辑了我的问题以包括父元素)。现在出现的错误是:“类型‘字符串’不可分配给类型‘”类别“|”Admin“”。“它位于地图内LinkItem的属性“name”中。谢谢,我明白我的问题必须非常基本:)
@GuillermoBrachetta Check my "Updated typescript demo"
@GuillermoBrachetta查看我的“更新打字稿演示”
That indeed cleared all errors, thank you! Now I'll try to digest it :D
这确实清除了所有的错误,谢谢!现在我要试着去消化它:D
我是一名优秀的程序员,十分优秀!