0

error message:"

"The element is implicitly of type "any" because an expression of type "string" cannot be used for indexing of type "IColorPokemonObj". No index signature found in type "IColorPokemonObj" with parameter of type "string" .ts (7053)"

<SubPopupPokemonImg styleBackground={{background: colorPokemonObj?.[type1]}}>



export const colorPokemonObj: IColorPokemonObj = {
   fire : '#D93E30',
   grass : '#7AC74C',
   electric : '#f2cb07',             
   water:'#35BAFF',
   ground:'#E2BF65',
   rock:'#B6A136',
   fairy: '#D685AD',
   poison: '#64D368',
   bug: '#A6B91A',
   dragon:'#6F35FC',
   psychic:'#F95587',
   flying:'#A98FF3' ,
   fighting:'#C22E28' ,
   normal:'#A8A77A' ,
   ice:'#96D9D6' ,
   ghost:'#735797' ,
   dark: '#705746' ,
   unknown: '#B7B7CE'
}


export interface IColorPokemonObj {
  fire: string;
  grass: string;
  electric: string;
  water: string;
  ground: string;
  rock: string;
  fairy: string;
  poison: string;
  bug: string;
  dragon: string;
  psychic: string;
  flying: string;
  fighting: string;
  'normal': string ,
  'ice': string ,
  'ghost':string ,
  'dark': string,
  'unknown': string
}

if you pass the call signature, then immediately yields the type any and error

HLEB HLEB
  • 128
  • 8
  • Does this answer your question? [Element implicitly has an 'any' type because expression of type 'string' can't be used to index](https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b) – Nicolas R Sep 13 '21 at 15:49

1 Answers1

0

To ensure type safety, typescript won't let you use any string to index your objects - you can only use actual keys of IColorPokemonObj.

You can change the type of your key type1:

let key1: string = 'fire';
const fireColorERROR = colorPokemonObj[key1];

let key2: keyof IColorPokemonObj = 'fire';
const fireColorOK = colorPokemonObj[key2];

Playground

There is also a feature called Index signatures which allows you to use any string as a key (which is useful when you don't know the shape of the object, but in your case the shape is well defined and you know all property names in advance)

Lesiak
  • 22,088
  • 2
  • 41
  • 65