Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
like image 494
Lehks Avatar asked May 08 '19 08:05

Lehks


People also ask

Can enum be array?

Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.

How do I get all the enum values in TypeScript?

To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.

What is the use of enum in TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.


Video Answer


3 Answers

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 = {}));
like image 101
marsibarsi Avatar answered Oct 13 '22 18:10

marsibarsi


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));
like image 8
Titian Cernicova-Dragomir Avatar answered Oct 13 '22 17:10

Titian Cernicova-Dragomir


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)

like image 5
Arnaud Leymet Avatar answered Oct 13 '22 16:10

Arnaud Leymet