Typescript enum values as array

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)


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

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