Konzy262
Konzy262

Reputation: 3097

Iterate over an enum with typescript and assign to an enum

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,

Upvotes: 4

Views: 32341

Answers (2)

LeOn - Han Li
LeOn - Han Li

Reputation: 10204

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.

Upvotes: 32

Jevgeni
Jevgeni

Reputation: 2574

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;
}

Upvotes: 15

Related Questions