44

Is it possible to get the values of an enum in TypeScript as an array?

Like this:

enum MyEnum {
    FOO = 'foo',
    BAR = 'bar'
}

becomes

['foo', 'bar']
Lehks
  • 2,582
  • 4
  • 19
  • 50

5 Answers5

61

Yes, it is possible to use:

Object.values(MyEnum)

because enum is an JS object after compilation:

var MyEnum;
(function (MyEnum) {
    MyEnum["FOO"] = "foo";
    MyEnum["BAR"] = "bar";
})(MyEnum || (MyEnum = {}));
marsibarsi
  • 973
  • 7
  • 7
11

For a fully typed code, you may want to infer the list of values as a type with some help of the template literal operator:

enum MyEnum {
    FOO = 'foo',
    BAR = 'bar'
}

type MyEnumValue = `${MyEnum}`
// => type MyEnumValue = "foo" | "bar"

const values: MyEnumValue[] = Object.values(MyEnum)
// => ["foo", "bar"]

Reference article: Get the values of an enum dynamically (disclaimer: author here)

Arnaud Leymet
  • 5,995
  • 4
  • 35
  • 51
8

The simplest way to do it for a string enum is to use Object.values

enum MyEnum {
    FOO = 'foo',
    BAR = 'bar'
}
console.log(Object.values(MyEnum));
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • this answer is in more detail https://stackoverflow.com/questions/39372804/how-can-i-loop-through-enum-values-for-display-in-radio-buttons – patelarpan Mar 22 '21 at 11:49
4

This function should work with numeric enums as well and it type-checks:

type EnumObject = {[key: string]: number | string};
type EnumObjectEnum<E extends EnumObject> = E extends {[key: string]: infer ET | string} ? ET : never;

function getEnumValues<E extends EnumObject>(enumObject: E): EnumObjectEnum<E>[] {
  return Object.keys(enumObject)
    .filter(key => Number.isNaN(Number(key)))
    .map(key => enumObject[key] as EnumObjectEnum<E>);
}

For example:

enum NumEnum {
    A,
    B,
    C,
}
// The type is inferred as NumEnum[]
let numEnumValues = getEnumValues(NumEnum);

TypeScript Playground

I've posted more details here: How to get an array of enum values in TypeScript

bgeyts668
  • 166
  • 1
  • 5
3

Edit:

Imho @Fyodor's solution is cleaner because it covers string enums:

const enumAsArray = Object.values(MyEnum).filter(value => typeof value === 'string')
Marco Nascimento
  • 832
  • 8
  • 15