11

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)

Screenshot

How can I fix that?

1
  • 3
    Spelling suggestion: it's spelled "suit" Commented Mar 24, 2023 at 19:22

2 Answers 2

20

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

Sign up to request clarification or add additional context in comments.

Comments

2

I want to point out at Connor Low's answer that on the second approach the value is not the string but the actual enum type, so you could do:

for(const [,suite] of Object.entries(Suite)) {
    doSuiteFunction(suite)
}

where doSuitFunction is defined as:

function doSuiteFunction(suite:Suite)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.