Lehks
Lehks

Reputation: 3166

Typescript enum values as array

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']

Upvotes: 53

Views: 60634

Answers (5)

bgeyts668
bgeyts668

Reputation: 166

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

Upvotes: 4

Arnaud Leymet
Arnaud Leymet

Reputation: 6122

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)

Upvotes: 12

Marco Nascimento
Marco Nascimento

Reputation: 1010

Edit:

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

const enumAsArray = Object.values(MyEnum).filter(value => typeof value === 'string')

Upvotes: 5

marsibarsi
marsibarsi

Reputation: 1073

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 = {}));

Upvotes: 69

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249606

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));

Upvotes: 7

Related Questions