首页 > 解决方案 > 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。

标签: javascriptreactjstypescriptloops

解决方案


此错误的原因是routestype 的参数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[]


推荐阅读