7

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?

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I want to retain the type as enum. I am editing your answer accordingly
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.
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'.
Element implicitly has an 'any' type because index expression is not of type 'number'.
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);

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.