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

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


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:

RedGreenBlue

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