1

I am trying to interface a map loop in JavaScript, what I have done is:

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

the code of the map loop is:

// 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>
      );
    });
  };

The error I cannot understand is the following

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

Could you help me understand this issue? Thanks, F.

1 Answer 1

1

The reason for this error is that the routes argument of type object[] cannot be cast to a type of RoutesType[].

The reason that TypeScript is attempting this type-cast is that type of routes is inferred and expected to be RoutesType[], due to the type of the prop argument on the map callback.

A fix would be to revise your createLinks function signature like this:

 /* 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>
      );
    });
  };

This change will require that all calls to createLink throughout your project specficy a routes value that is strictly typed to RoutesType[]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.