Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a typescript enum into an array of enums

Tags:

typescript

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?

like image 523
suku Avatar asked Dec 06 '22 11:12

suku


2 Answers

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.

like image 158
toskv Avatar answered Dec 09 '22 15:12

toskv


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);
like image 39
DANI Fouad Avatar answered Dec 09 '22 13:12

DANI Fouad