4

I am attempting to iterate over all the values in an enum, and assign each value to a new enum. This is what I came up with....

enum Color {
    Red, Green
}

enum Suit { 
    Diamonds, 
    Hearts, 
    Clubs, 
    Spades 
}

class Deck 
{
    cards: Card[];

    public fillDeck() {
        for (let suit in Suit) {
            var mySuit: Suit = Suit[suit];
            var myValue = 'Green';
            var color : Color = Color[myValue];
        }
    }
}

The part var mySuit: Suit = Suit[suit]; doesn't compile, and returns the error Type 'string' is not assignable to type 'Suit'.

If I hover over suit in the for loop, it shows me let suit: string. var color : Color = Color[myValue]; also compiles without error. What am I doing wrong here as both examples with Suit and Color look identical to me.

I'm on TypeScript version 2.9.2 and this is the contents of my tsconfig.json

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "sourceMap": true
    }
}

Is there a better way to iterate over all the values in an enum, whilst maintaining the enum type for each iteration?

Thanks,

2 Answers 2

32

For string enum, if the strict flag is on, we will get type string can't be used to index type 'typeof Suit'. So we have to something like:

for (const suit in Suit) {
    const mySuit: Suit = Suit[suit as keyof typeof Suit];
}

If you just need the string value of it, then use suit directly is fine.

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

Comments

15

You can either use this hack:

const mySuit: Suit = Suit[suit] as any as Suit;

or change Suit enum to string enum and use it like this:

enum Suit { 
    Diamonds = "Diamonds", 
    Hearts = "Hearts", 
    Clubs = "Clubs", 
    Spades = "Spades",
}

for (let suit in Suit) {
    const mySuit: Suit = Suit[suit] as Suit;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.