简体   繁体   中英

TypeScript error Element implicitly has an 'any' type because expression of type 'any' can't be used to index type

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?

When a raw object is defined in Typescript (eg CATEGORY_LABELS) - it won't allow for indexed access (eg 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',
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM