javascript - React Typescript地图循环接口错误
问题描述
我正在尝试在 JavaScript 中连接地图循环,我所做的是:
interface RoutesType {
path: string;
name: string;
icon: string;
layout: string;
}
地图循环的代码是:
// 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。
解决方案
此错误的原因是routes
type 的参数object[]
不能转换为RoutesType[]
.
TypeScript 尝试进行这种类型转换的原因是,由于映射回调中参数的类型,类型 ofroutes
被推断并预期为。RoutesType[]
prop
一个修复方法是修改你的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[]
推荐阅读
- variables - 是否有一种语言可以声明变量并启用所述变量的共轭?
- reactjs - 通知前端后端的变化
- vb.net - 在 taglib-sharp 中使用“Beats per minute”的小数位
- firebase - Firestore docRef.get() 调用生成的这些“重试请求”日志是什么?
- c++ - 诅咒 C++ 的问题
- json - 异常类型'列表
' 不是类型 'List 的子类型 ' 在 Flutter 应用程序中进行类型转换 - google-kubernetes-engine - GKE + Istio 入口 + 证书管理器
- python - Rasa Chatbot 无法响应用户输入
- r - 在某些条件下随机选择R中的行
- css - 响应式 CSS 浪潮?