Home > Software engineering >  TypeScript error Element implicitly has an 'any' type because expression of type 'any
TypeScript error Element implicitly has an 'any' type because expression of type 'any

Time:12-22

I am getting this error:

  Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ foo: string; bar: string; }'.ts(7053)

In this code:

const CATEGORY_COLORS = {
  foo: '#6f79F6',
  bar: '#4fA0E9',
};

const CATEGORY_LABELS = {
  foo: 'FOO',
  bar: 'BAR',
};

const ItemRenderer = ({ item }: ItemRendererPropsType): React.ReactElement => {
  return (
    <div>
      <Tag color={CATEGORY_COLORS[item.category]}>
        {CATEGORY_LABELS[item.category]}
      </Tag>
    </div>
  );
};

The error is when I hover over either CATEGORY_COLORS[item.category] or CATEGORY_LABELS[item.category] with TypeScript. How do I resolve?

CodePudding user response:

When a raw object is defined in Typescript (e.g. CATEGORY_LABELS) - it won't allow for indexed access (e.g. CATEGORY_LABELS[key]) where key is a string. In your example, I assume that item.category is of type string.

Either item.category should be of type keyof typeof CATEGORY_LABELS or you need to redefine CATEGORY_LABELS to allow for indexing by a random string, but that is less typesafe, since you aren't guaranteeing that you will pass in a valid key.

const CATEGORY_LABELS: Record<string, string> = {
  foo: 'FOO',
  bar: 'BAR',
};
  • Related