I have next enum:
export enum Suite {
Spade = '♠',
Heart = '♥',
Club = '♣',
Diamond = '♦',
}
Trying to implement loop, but getting error
for (let suite in Suite) {
console.log('item:', Suite[suite]);
}
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Suite'. No index signature with a parameter of type 'string' was found on type 'typeof Suite'.ts(7053)

How can I fix that?
You need to narrow the type of your suite key with a type constraint. You can do this by declaring it before the loop:
enum Suite {
Spade = '♠',
Heart = '♥',
Club = '♣',
Diamond = '♦',
}
let suite: keyof typeof Suite;
for (suite in Suite) {
const value = Suite[suite];
// ...
}
Or use Object.entries:
for (const [key, value] of Object.entries(Suite)) {
// key = Spade, etc.
// value = ♠, etc.
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With