Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type error when passing props to component

Hello I have a type that looks like this:

type MenuItemType = { name: string; link: string };

Also an array of those types:

const menuItems: MenuItemType[] = [
    { name: "FAQ", link: "/faq" },
    { name: "Terms of use", link: "/terms" },
    { name: "Cookie policy", link: "/cookie-policy" },
    { name: "Privacy policy", link: "/privacy-policy" },
    { name: "Subscription", link: "/subscription" },
];

And a component that takes some props that are of this same type:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function ListItem({ name, link }: MenuItemType) {
    return (
        <li className="text-xs mr-14 last:mr-0">
            <Link href={link}>
                <a>{name}</a>
            </Link>
        </li>
    );
}

The ListItem Component is rendered in a map function, and this is where typescript is complaining.

enter image description here

What am i doing wrong?

>Solution :

You’ve defined your ListItem component so it expects separate props for the name and link, not a combined prop of the item. So if ListItem is correct, you’ll use it like this:

<ListItem name={item.name} link={item.link} />
// or:
<ListItem {...item} />

Alternatively, if you want to pass in a single item prop, rewrite ListItem to this:

function ListItem({ item }: { item: MenuItemType }) {
    return (
        <li className="text-xs mr-14 last:mr-0">
            <Link href={item.link}>
                <a>{item.name}</a>
            </Link>
        </li>
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading