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']
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.
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.
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.
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 = {}));
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));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With