Peter V. Mørch
Peter V. Mørch

Reputation: 15937

Iterate over enum as named constants (not values!)

I've found many posts about how to get an array of possible values for TypeScript enums, but I want an array of the typed named constants.

And it is very possible this TypeScript newbie is using the wrong terms/words and that this is part of the problem...

enum Color {
    RED = "red",
    GREEN = "green"
}

// Object.keys(Color) gives me ["RED", "GREEN"] as strings but I want:
const allColors = new Array<Color>(Color.RED, Color.GREEN);

function takesColor(color: Color) {
    console.log("Color is", color);
}

// So I can iterate over all colors and call takesColor() like so:
for (let color of allColors) {
    takesColor(color);
}

How do I create allColors without explicity listing every member? My allColors above isn't DRY.

Upvotes: 2

Views: 68

Answers (1)

Rich N
Rich N

Reputation: 9475

Try:

// These two are the same type
const allColors : Color[] = new Array<Color>(Color.RED, Color.GREEN);
const allColors2: Color[] = Object.values(Color);

If you put a break in you'll see that allColors and allColors2 are the same array (["red", "green"]), and you haven't had to list all the members to create allColors2.

Upvotes: 1

Related Questions