54

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

5 Answers 5

71

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 = {}));
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is not correct for number enums
13

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)

1 Comment

This answer is not correct for number enums
7

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

1 Comment

this answer is in more detail stackoverflow.com/questions/39372804/…
5

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

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

3 Comments

Or const enumAsArray = Object.values(MyEnum).filter(value => typeof value === 'string') (replace 'string' with necessary type) To remove indexes I mean
Also a nice approach :)
This looks weird.. Why cut half of values? What if we have odd length? Splice is definitely not needed.
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

1 Comment

This will not work for ` enum X { "012" = 1 } `

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.