76

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?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347

1 Answers1

110

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
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • 15
    why not just write `Object.values(Color)` – pavle Jul 17 '20 at 12:56
  • 2
    @pavle `Object.values` is part of ECMAScript 2017. The `Object.keys` is part of ECMAScript 2015 / ES5. – k0pernikus Aug 05 '20 at 14:28
  • 1
    @pavle Added it to my answer, thanks for pointing it out. – k0pernikus Aug 05 '20 at 14:30
  • 8
    Like @k0pernikus said, TypeScript enums is compiled in a way it allows to lookup to an index from a value. So `Object.keys` and `Object.values` return an array with same values (regardless the type). I use `Object.keys(Color).filter(k => isNaN(Number(k)));` to get my enum keys list. – Mason Jan 15 '21 at 20:59
  • 3
    Actually, Object.values(Color) could return a key if the value is a number and your enum is a string. Example: ` enum StringEnum { First = 'First Value', Second = 'Second Value', Third = 4 } ` would return `Third` with the values. – T. Dayya Sep 27 '21 at 09:09
  • Object.values(COLLECTIONS).filter(isNaN as any) – ThomasP1988 Feb 21 '22 at 15:30
  • 2
    Can't post another answer here and the linked "duplicate" is a different question. Here's k0pernikus's method wrapped into a generic function: [How to get an array of enum values in TypeScript](https://blog.oyam.dev/typescript-enum-values/) – bgeyts668 Mar 20 '22 at 12:37