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

Typescript – Type 'String' Can't Be Used To Index – React Dynamic Component Name Map

I’ve got the following working and I’m trying to convert it to Typescript but whilst I somewhat understand the error, I’m not sure how to go about actually fixing it.

I am currently allowing a component to have a prop of "icon" which is a string and this string is then translating to a component name to be loaded.

icons/index.ts

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

import { BellIcon } from "./BellIcon";

export const iconMap = {
  BellIcon
};

iconButton.tsx

import { iconMap } from "./icons";

type IconButtonProps = {
  icon: string;
  label?: string;
  direction?: string;
  onClick: () => void;
};

The offending line:

const IconElement = iconMap[icon];

This is what I get as the two errors:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ BellIcon: (props: any) => Element; }'.
No index signature with a parameter of type 'string' was found on type '{ BellIcon: (props: any) => Element; }'.ts(7053)

Further down the page then for context I am calling the following to get the dynamic component loaded:

<IconElement />

I’ve tried setting various types but can’t find anything that solves the problem, was more trying to guess and I’d actually like to understand the issue.

>Solution :

You need to change the type of the icon prop to only accept keys of the iconMap object.

import { iconMap } from "./icons";

type IconButtonProps = {
  icon: keyof typeof iconMap;
  label?: string;
  direction?: string;
  onClick: () => void;
};
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