0

I have an object like this

const mockDropdown = [{
  icon: 'MdMonitor',
  label: 'Television',
}];

When i use this component i have this warning:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("/home/user/projectUnknown/node_modules/react-icons/md/index")'.

In this line

const mdIcon = MaterialDesign[item.icon];

This is the component

import { createElement } from 'react';
import * as MaterialDesign from 'react-icons/md';

interface DataIcon {
  icon: string;
  label: string;
}

interface AdvancedProps {
  data: Array<DataIcon>;
}

export default function Advanced({
  data,
}: AdvancedProps) {
  return (
    <ul>
      {data && data.map((item) => {
        const mdIcon = MaterialDesign[item.icon];
        return (
          <li>
            <button type="button">{createElement(mdIcon)}</button>
            <p>{item.label}</p>
          </li>
        );
      })}
    </ul>
  );
}

vazquezdev
  • 41
  • 6
  • 1
    Are you sure you want to load all these icons at once instead of only those that you will use? – Konrad Aug 23 '22 at 19:43
  • `ìtem.icon` is typed just as `string`, so there is no guarantee that it exists inside the `MaterialDesign` object. – Camilo Aug 23 '22 at 19:58
  • Does this answer your question? [TypeScript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type](https://stackoverflow.com/questions/57438198/typescript-element-implicitly-has-an-any-type-because-expression-of-type-st) – Heretic Monkey Aug 23 '22 at 20:02
  • searching for the error goes a long way... – Heretic Monkey Aug 23 '22 at 20:03

1 Answers1

-1

You have to add const assertion to ensure TypeScript that this array won't change.

const mockDropdown = [{
  icon: 'MdMonitor',
  label: 'Television',
}] as const;
Konrad
  • 21,590
  • 4
  • 28
  • 64