Search code examples
typescriptiteratorsymbols

Symbol.iterator for enum values in Typescript


I would like to use the Symbol.iterator for an enum to iterate over its values like this:

enum Color {red, green, blue}

Color[Symbol.iterator] = function*():Iterator<Color> {
        yield Color.red;
        yield Color.green;
        yield Color.blue;
    }

for (let color of Color){
 alert(color);
}

But this does not work. What will work? Most important for me is not having to change the for/of line.

The error I got on the for/of line: TS2488: Type must have a 'Symbol.iterator' method that returns an iterator.


Solution

  • The closest I can get is:

    enum Color {red, green, blue}
    
    module Color 
    {
        export function* Values() 
        {
            yield Color.red;
            yield Color.green;
            yield Color.blue;
        }
    }
    
    for (let color of Color.Values())
    {
        alert(color);
    }
    

    Although it does slightly modifies your for/of loop. Hopefully it will be of any help to you.