6

I have an enum

export enum A{
   X = 'x',
   Y = 'y',
   Z = 'z'
}

I want this to be converted to

[A.X, A.Y, A.Z]

Type of the array is A[]. How to do this?

suku
  • 10,507
  • 16
  • 75
  • 120

2 Answers2

13

You can use Object.keys to get the keys of the enum and use them to get all the values.

It would look something like this.

let arr: A[] = Object.keys(A).map(k => A[k])

You can see it working here.

suku
  • 10,507
  • 16
  • 75
  • 120
toskv
  • 30,680
  • 7
  • 72
  • 74
  • 1
    I want to retain the type as enum. I am editing your answer accordingly – suku Sep 28 '18 at 11:38
  • 3
    I believe you can use `Object.values(A)` as well, to avoid unnecessary mapping. Enum is compiled to just an object, thats why both `keys` and `values` methods work here. – Matt Leonowicz Oct 03 '19 at 09:33
  • 6
    `Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof A'. No index signature with a parameter of type 'string' was found on type 'typeof A'.` – Piotr Siupa Aug 20 '20 at 08:33
  • `Element implicitly has an 'any' type because index expression is not of type 'number'.` – aurelia Aug 08 '22 at 19:49
4

You can use Object.values to get value of enum

enum A {
  X = 'x',
  Y = 'y',
  Z = 'z'
}
let arr = Object.values(A)
console.log(arr);
fdani
  • 41
  • 4
  • ([Matt Leonowicz assumed so](https://stackoverflow.com/questions/52554208/convert-a-typescript-enum-into-an-array-of-enums#comment102808662_52554378)) – greybeard Dec 29 '20 at 16:15