typescript 通过枚举名称字符串获取枚举值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38719483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get enum values by enum name string
提问by Jochen Kühner
In Typescript I get a stringvariable that contains the name of my defined enum.
在 Typescript 中,我得到一个string变量,其中包含我定义的enum.
How can I now get all values of this enum?
我现在怎样才能获得这个枚举的所有值?
采纳答案by mixel
Typescript enum:
打字稿枚举:
enum MyEnum {
First, Second
}
is transpiled to JavaScript object:
被转换为 JavaScript 对象:
var MyEnum;
(function (MyEnum) {
MyEnum[MyEnum["First"] = 0] = "First";
MyEnum[MyEnum["Second"] = 1] = "Second";
})(MyEnum || (MyEnum = {}));
You can get enuminstance from window["EnumName"]:
您可以enum从window["EnumName"]以下位置获取实例:
const MyEnumInstance = window["MyEnum"];
Next you can get enum member values with:
接下来,您可以通过以下方式获取枚举成员值:
const enumMemberValues: number[] = Object.keys(MyEnumInstance)
.map((k: any) => MyEnumInstance[k])
.filter((v: any) => typeof v === 'number').map(Number);
And enum member names with:
和枚举成员名称:
const enumMemberNames: string[] = Object.keys(MyEnumInstance)
.map((k: any) => MyEnumInstance[k])
.filter((v: any) => typeof v === 'string');
See also How to programmatically enumerate an enum type in Typescript 0.9.5?
回答by dimitrisli
As an alternative to the windowapproach that the other answers offer, you could do the following:
作为window其他答案提供的方法的替代方法,您可以执行以下操作:
enum SomeEnum { A, B }
let enumValues:Array<string>= [];
for(let value in SomeEnum) {
if(typeof SomeEnum[value] === 'number') {
enumValues.push(value);
}
}
enumValues.forEach(v=> console.log(v))
//A
//B

