2

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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Peter V. Mørch
  • 13,830
  • 8
  • 69
  • 103

1 Answers1

1

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.

Peter V. Mørch
  • 13,830
  • 8
  • 69
  • 103
Rich N
  • 8,939
  • 3
  • 26
  • 33
  • Ahhh. I now see that your `allColors2` variable has the compile-time Typescript type `Color[]` and not as I thought: `string[]`. I've taken the liberty of updating your code example to make that even clearer... – Peter V. Mørch Mar 18 '20 at 09:49
  • That's fine. The point @Erik Philips is making (whilst forgetting to answer the question!) is that Color[] IS string[] in the underlying JavaScript, and the TypeScript compiler is trying to pretend we have proper enum support by putting a layer on top of that. If you've come from a language which has native enums you'll find the TypeScript enums are a bit tricky as a result. – Rich N Mar 18 '20 at 10:05
  • Color[] is string[] *at runtime* not at compile time. – Erik Philips Mar 18 '20 at 20:00