typescript 如何获取枚举条目的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18111657/
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
How to get names of enum entries?
提问by CalvinDale
I would like to iterate a TypeScript an enum
type and get each enumerated symbol name, e.g.:
我想迭代一个 TypeScript 一个enum
类型并获取每个枚举的符号名称,例如:
enum myEnum { entry1, entry2 }
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
采纳答案by Judah Gabriel Himango
The code you posted will work; it will print out all the members of the enum, including the values of the enum members. For example, the following code:
您发布的代码将起作用;它将打印出枚举的所有成员,包括枚举成员的值。例如,以下代码:
enum myEnum { bar, foo }
for (var enumMember in myEnum) {
console.log("enum member: ", enumMember);
}
Will print the following:
将打印以下内容:
Enum member: 0
Enum member: 1
Enum member: bar
Enum member: foo
If you instead want only the member names, and not the values, you could do something like this:
如果您只需要成员名称,而不需要值,则可以执行以下操作:
for (var enumMember in myEnum) {
var isValueProperty = parseInt(enumMember, 10) >= 0
if (isValueProperty) {
console.log("enum member: ", myEnum[enumMember]);
}
}
That will print out just the names:
这将只打印出名称:
Enum member: bar
Enum member: foo
枚举成员:bar
枚举成员:foo
Caveat: this slightly relies on an implementation detail: TypeScript compiles enums to a JS object with the enum values being members of the object. If TS decided to implement them different in the future, the above technique could break.
警告:这稍微依赖于一个实现细节:TypeScript 将枚举编译为一个 JS 对象,枚举值是该对象的成员。如果 TS 决定在未来以不同的方式实现它们,上述技术可能会失效。
回答by shakram02
回答by Ryan Cavanaugh
Assuming you stick to the rules and only produce enums with numeric values, you can use this code. This correctly handles the case where you have a name that is coincidentally a valid number
假设您遵守规则并且只生成带有数值的枚举,您可以使用此代码。这可以正确处理您的名称恰好是有效数字的情况
enum Color {
Red,
Green,
Blue,
"10" // wat
}
var names: string[] = [];
for(var n in Color) {
if(typeof Color[n] === 'number') names.push(n);
}
console.log(names); // ['Red', 'Green', 'Blue', '10']
回答by Michael Erickson
For me an easier, practical and direct way to understand what is going on, is that the following enumeration:
对我来说,了解正在发生的事情的更简单、实用和直接的方法是以下枚举:
enum colors { red, green, blue };
Will be converted essentially to this:
将基本上转换为:
var colors = { red: 0, green: 1, blue: 2,
[0]: "red", [1]: "green", [2]: "blue" }
Because of this, the following will be true:
因此,以下情况为真:
colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0
This creates a easy way to get the name of an enumerated as follows:
这创建了一种获取枚举名称的简单方法,如下所示:
var color: colors = colors.red;
console.log("The color selected is " + colors[color]);
It also creates a nice way to convert a string to an enumerated value.
它还创建了一种将字符串转换为枚举值的好方法。
var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];
The two situations above are far more common situation, because usually you are far more interested in the name of a specific value and serializing values in a generic way.
上述两种情况是更常见的情况,因为通常您对特定值的名称和以通用方式序列化值更感兴趣。
回答by Simon
If you only search for the names and iterate later use:
如果您只搜索名称并稍后迭代,请使用:
Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];
回答by Philip
With current TypeScript Version 1.8.9 I use typed Enums:
在当前的 TypeScript 版本 1.8.9 中,我使用类型化枚举:
export enum Option {
OPTION1 = <any>'this is option 1',
OPTION2 = <any>'this is option 2'
}
with results in this Javascript object:
结果在这个 Javascript 对象中:
Option = {
"OPTION1": "this is option 1",
"OPTION2": "this is option 2",
"this is option 1": "OPTION1",
"this is option 2": "OPTION2"
}
so I have to query through keys and values and only return values:
所以我必须通过键和值查询并且只返回值:
let optionNames: Array<any> = [];
for (let enumValue in Option) {
let optionNameLength = optionNames.length;
if (optionNameLength === 0) {
this.optionNames.push([enumValue, Option[enumValue]]);
} else {
if (this.optionNames[optionNameLength - 1][1] !== enumValue) {
this.optionNames.push([enumValue, Option[enumValue]]);
}
}
}
And I receive the option keys in an Array:
我在数组中收到选项键:
optionNames = [ "OPTION1", "OPTION2" ];
回答by John Huebner
As of TypeScript 2.4, enums can contain string intializers https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html
从 TypeScript 2.4 开始,枚举可以包含字符串初始化器https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html
This allows you to write:
这允许您编写:
enum Order {
ONE = "First",
TWO = "Second"
}
console.log(`One is ${Order.ONE.toString()}`);
and get this output:
并得到这个输出:
One is First
一个是第一
回答by Carlinhos
This solution work too.
这个解决方案也有效。
enum ScreenType {
Edit = 1,
New = 2,
View = 4
}
var type: ScreenType = ScreenType.Edit;
console.log(ScreenType[type]); //Edit
回答by manzapanza
Another interesting solution found hereis using ES6 Map:
另一个有趣的解决方案在这里找到使用ES6地图:
export enum Type {
low,
mid,
high
}
export const TypeLabel = new Map<number, string>([
[Type.low, 'Low Season'],
[Type.mid, 'Mid Season'],
[Type.high, 'High Season']
]);
USE
用
console.log(TypeLabel.get(Type.low)); // Low Season
回答by Jeff Lau
Let ts-enum-util
(github, npm) do the work for you and provide a lot of additional type-safe utilities. Works with both string and numeric enums, properly ignoring the numeric index reverse lookup entries for numeric enums:
让ts-enum-util
(github,npm)为您完成工作并提供许多额外的类型安全实用程序。适用于字符串和数字枚举,正确忽略数字枚举的数字索引反向查找条目:
String enum:
字符串枚举:
import {$enum} from "ts-enum-util";
enum Option {
OPTION1 = 'this is option 1',
OPTION2 = 'this is option 2'
}
// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();
// type: Option[]
// value: ["this is option 1", "this is option 2"]
const values = $enum(Option).getValues();
Numeric enum:
数字枚举:
enum Option {
OPTION1,
OPTION2
}
// type: ("OPTION1" | "OPTION2")[]
// value: ["OPTION1", "OPTION2"]
const keys= $enum(Option).getKeys();
// type: Option[]
// value: [0, 1]
const values = $enum(Option).getValues();