如何以编程方式枚举枚举类型? [英] How to programmatically enumerate an enum type?
问题描述
假设我有一个TypeScript 枚举
, MyEnum
,如下所示:
Say I have a TypeScript enum
, MyEnum
, as follows:
enum MyEnum {
First,
Second,
Third
}
在TypeScript 0.9.5中生成 enum
数组的最佳方法是什么?价值观?示例:
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?
推荐答案
这是该枚举的JavaScript输出:
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 = {}));
哪个对象是这样的:
{
"0": "First",
"1": "Second",
"2": "Third",
"First": 0,
"Second": 1,
"Third": 2
}
具有字符串值的枚举成员
TypeScript 2.4添加了枚举可能具有字符串枚举成员值的功能。因此,可能最终得到如下所示的枚举:
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 = {}));
获取会员名
我们可以看看上面的示例试图弄清楚如何获得枚举成员:
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"
}
这是我想出的内容:
const e = MyEnum as any;
const names = Object.keys(e).filter(k =>
typeof e[k] === "number"
|| e[k] === k
|| e[e[k]]?.toString() !== k
);
成员值
一旦名称,我们可以通过以下操作遍历它们以获得相应的值:
Once, we have the names, we can loop over them to get the corresponding value by doing:
const values = names.map(k => MyEnum[k]);
扩展类
我认为最好的方法为此,是创建自己的函数(例如 EnumEx.getNames(MyEnum)
)。您不能向枚举添加函数。
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);
}
}
这篇关于如何以编程方式枚举枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!