gpt4 book ai didi

javascript - React Typescript 映射循环接口(interface)错误

转载 作者:行者123 更新时间:2023-11-30 19:13:44 25 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中连接一个 map 循环,我所做的是:

interface RoutesType {
path: string;
name: string;
icon: string;
layout: string;
}

map 循环的代码是:

// creates the links that appear in the left menu / Sidebar
const createLinks = (routes: object[]) => {
return routes.map((prop: RoutesType, key: number) => {
return (
<NavItem key={key}>
<NavLink to={prop.layout + prop.path} tag={NavLinkRRD} onClick={closeCollapse} activeClassName="active">
<i className={prop.icon} />
{prop.name}
</NavLink>
</NavItem>
);
});
};

我无法理解的错误如下

TypeScript error: Argument of type '(prop: RoutesType, key: number) => Element' is not assignable to parameter of type '(value: object, index: number, array: object[]) => Element'.
Types of parameters 'prop' and 'value' are incompatible.
Type '{}' is missing the following properties from type 'RoutesType': path, name, icon, layout

你能帮我理解这个问题吗?谢谢,F.

最佳答案

出现此错误的原因是 object[] 类型的 routes 参数无法转换为 RoutesType[] 类型。

TypeScript 尝试这种类型转换的原因是 routes 的类型被推断并预期为 RoutesType[],因为 的类型>prop map 回调参数。

一个修复方法是像这样修改您的 createLinks 函数签名:

 /* Update routes to RoutesType[] */
const createLinks = (routes: RoutesType[]) => {
return routes.map((prop: RoutesType, key: number) => {
return (
<NavItem key={key}>
<NavLink to={prop.layout + prop.path} tag={NavLinkRRD}
onClick={closeCollapse} activeClassName="active">
<i className={prop.icon} />
{prop.name}
</NavLink>
</NavItem>
);
});
};

此更改将要求在整个项目中对 createLink 的所有调用都指定一个 routes 值,该值严格键入 RoutesType[]

关于javascript - React Typescript 映射循环接口(interface)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com