Iterate over an enum with typescript and assign to an enum

21,496

Solution 1

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

Solution 2

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.

Share:
21,496
Konzy262
Author by

Konzy262

Updated on October 23, 2020

Comments

  • Konzy262
    Konzy262 over 3 years

    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,