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

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Categories: Element; Admin: Element; }'

I’m quite new to TS and would like to understand why I get a type error in the following code (simplified):

"use client";

import { ArrowDownWideNarrow, Settings } from "lucide-react";

interface LinkItemProps {
  name: string;
}

const iconMap = {
  Categories: <ArrowDownWideNarrow />,
  Admin: <Settings />,
};

export const LinkItem = ({ name }: LinkItemProps) => {
  <div>
    {iconMap[name]}
  </div>
}

The error is in the `{iconMap[name]}:

"Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Categories: Element; Admin: Element; }'.

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

No index signature with a parameter of type 'string' was found on type '{ Categories: Element; Admin: Element; }'."

The parent element has the following:

const LINKS = [
  {
    href: "/admin",
    name: "Admin",
    id: "admin",
  },
  {
    href: "/categories",
    name: "Categories",
    id: "categories",
  },
];

export const Sidebar = async () => {
  return (
    <div>
      {LINKS.map((link) => (
        <div key={link.href}>
          <LinkItem href={link.href} id={link.id} name={link.name} />
        </div>
      ))}
    </div>
  )
}

>Solution :

No index signature with a parameter of type ‘string’ was found on type ‘{ Categories: Element; Admin: Element; }’."

The string type is too wide, you could be more specific on the name prop type so it properly inherits the fields based on the iconMap object.

Typescript demo

interface LinkItemProps {
  name: keyof typeof iconMap;
}

or a manual, strictly typed approach:

interface LinkItemProps {
  name: 'Categories' | 'Admin';
}

Updated typescript demo

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