suku
suku

Reputation: 10929

Convert a typescript enum into an array of enums

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?

Upvotes: 7

Views: 15337

Answers (2)

fdani
fdani

Reputation: 41

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

Upvotes: 4

toskv
toskv

Reputation: 31600

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.

Upvotes: 13

Related Questions