I'm trying to loop over the keys of an object and attach the value as id / for now console.log() it. I receive the following error:
- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'StartItems'. No index signature with a parameter of type 'string' was found on type 'StartItems'
Now I thought I have my Interface set up correctly, but somehow Typescript doesnt understand that the placeholder "key" in my loop contains the valid "key" defined in the interface. Here's the code:
/* Some Notes:
* heroStartItems[GameSettings.heroId] returns the correct object
* heroStartItems[GameSettings.heroId][key] compiles successfully although
the TS error message.
*/
// the loop in which the error occurs.
for (const key in heroStartItems[GameSettings.heroId]) {
const div = document.createElement('div');
//const img = document.createElement('img');
div.classList.add(key);
console.log(heroStartItems[GameSettings.heroId][key]);
//div.id = heroStartItems[key].toString();
// div.appendChild(img);
heroItems.appendChild(div);
}
// heroStartItems looks like this:
export const heroStartItems: heroItemSlots = {
[Heroes['Anti-Mage']]: {
item1: ItemsEnum['Tango'],
item2: ItemsEnum['Healing Salve'],
item3: ItemsEnum['Quelling Blade'],
item4: ItemsEnum['Iron Branch'],
item5: ItemsEnum['Iron Branch'],
item6: ItemsEnum['Slippers of Agility'],
},
.
.
.
}
// heroItemSlots looks like this:
export interface heroItemSlots {
[key: string]: StartItems;
}
interface StartItems {
item1: number | null;
item2: number | null;
item3: number | null;
item4: number | null;
item5: number | null;
item6: number | null;
}
After compiling, I receive the correct output, which are the numbers of ItemsEnum.
I have tried to implement a typeguard inside the for loop like so:
if (key instanceof StartItems) {
console.log(heroStartItems[GameSettings.heroId][key]);
}
But the error persists. I'm pretty lost here and sure that I do miss some key concepts of Typescript. I appreciate any help. Thanks in advance!