Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the values of an enum with typescript? [duplicate]

Tags:

Given an a TypeScript enum:

export enum Color {     Red,     Green,     Blue, } 

I want to get all its values in an array like so:

["Red", "Green", "Blue"] 

Yet when I work on that enum with

const colors = Object.keys(Color); 

I get weird array consisting of its index and value:

[ '0', '1', '2', 'Red', 'Green', 'Blue' ] 

Why is this the case and how can I only get the values?

like image 891
k0pernikus Avatar asked Feb 13 '18 14:02

k0pernikus


People also ask

How do I get all the enum values in TypeScript?

To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can you loop through enum JavaScript?

Iterating over the keys Of course, it's also possible to loop over the keys of a string enum, using Object.


1 Answers

You have to filter out the numeric keys, either via Object.values or Object.keys:

const colors = Object.keys(Color).filter((item) => {     return isNaN(Number(item)); }); console.log(colors.join("\n")); 

This will print:

Red Green Blue 

A TypeScript enum will transpile in the end into a plain JavaScript object:

{    '0': 'Red',    '1': 'Green',   '2': 'Blue',   Red: 0,   Green: 1,   Blue: 2 } 

So you can use the numeric index as key to get the value, and you can use the value to lookup its index in the enum:

console.log(Color[0]); // "Red" console.log(Color["0"]); // "Red" console.log(Color["Red"]) // 0 
like image 86
k0pernikus Avatar answered Oct 08 '22 09:10

k0pernikus