Reputation: 324
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.
Upvotes: 1
Views: 612
Reputation: 30360
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[]
Upvotes: 1