Say I have a TypeScript enum
, MyEnum
, as follows:
enum MyEnum { First, Second, Third }
What would be the best way in TypeScript 0.9.5 to produce an array of the enum
values? Example:
var choices: MyEnum[]; // or Array<MyEnum> choices = MyEnum.GetValues(); // plans for this? choices = EnumEx.GetValues(MyEnum); // or, how to roll my own?
An enum can be looped through using Enum. GetNames<TEnum>() , Enum. GetNames() , Enum.
Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics.
This is the JavaScript output of that enum:
var MyEnum; (function (MyEnum) { MyEnum[MyEnum["First"] = 0] = "First"; MyEnum[MyEnum["Second"] = 1] = "Second"; MyEnum[MyEnum["Third"] = 2] = "Third"; })(MyEnum || (MyEnum = {}));
Which is an object like this:
{ "0": "First", "1": "Second", "2": "Third", "First": 0, "Second": 1, "Third": 2 }
Enum Members with String Values
TypeScript 2.4 added the ability for enums to possibly have string enum member values. So it's possible to end up with an enum that look like the following:
enum MyEnum { First = "First", Second = 2, Other = "Second" } // compiles to var MyEnum; (function (MyEnum) { MyEnum["First"] = "First"; MyEnum[MyEnum["Second"] = 2] = "Second"; MyEnum["Other"] = "Second"; })(MyEnum || (MyEnum = {}));
Getting Member Names
We can look at the example immediately above to try to figure out how to get the enum members:
{ "2": "Second", "First": "First", "Second": 2, "Other": "Second" }
Here's what I came up with:
const e = MyEnum as any; const names = Object.keys(e).filter(k => typeof e[k] === "number" || e[k] === k || e[e[k]]?.toString() !== k );
Member Values
Once, we have the names, we can loop over them to get the corresponding value by doing:
const values = names.map(k => MyEnum[k]);
Extension Class
I think the best way to do this is to create your own functions (ex. EnumEx.getNames(MyEnum)
). You can't add a function to an enum.
class EnumEx { private constructor() { } static getNamesAndValues(e: any) { return EnumEx.getNames(e).map(n => ({ name: n, value: e[n] as string | number })); } static getNames(e: any) { return Object.keys(e).filter(k => typeof e[k] === "number" || e[k] === k || e[e[k]]?.toString() !== k ); } static getValues(e: any) { return EnumEx.getNames(e).map(n => e[n] as string | number); } }
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