我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
当前回答
根据TypeScript文档,我们可以通过Enum和静态函数来实现这一点。
使用静态函数获取Enum名称
enum myEnum {
entry1,
entry2
}
namespace myEnum {
export function GetmyEnumName(m: myEnum) {
return myEnum[m];
}
}
now we can call it like below
myEnum.GetmyEnumName(myEnum.entry1);
// result entry1
要阅读更多关于Enum的静态函数,请点击下面的链接 https://basarat.gitbooks.io/typescript/docs/enums.html
其他回答
当我遇到同样的问题时,你可以使用我写的enum-values包:
Git: enum-values
var names = EnumValues.getNames(myEnum);
在当前的TypeScript版本1.8.9中,我使用类型化enum:
export enum Option {
OPTION1 = <any>'this is option 1',
OPTION2 = <any>'this is option 2'
}
与结果在这个Javascript对象:
Option = {
"OPTION1": "this is option 1",
"OPTION2": "this is option 2",
"this is option 1": "OPTION1",
"this is option 2": "OPTION2"
}
所以我必须通过键和值查询,只返回值:
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]]);
}
}
}
我在数组中收到选项键:
optionNames = [ "OPTION1", "OPTION2" ];
我通过搜索“TypeScript iterate over enum keys”找到了这个问题。所以我只想给出对我来说有用的解。也许对别人也有帮助。
我的情况如下:我想在每个枚举键上迭代,然后过滤一些键,然后访问一些对象,其中键作为枚举的计算值。这就是没有TS误差的方法。
enum MyEnum = { ONE = 'ONE', TWO = 'TWO' }
const LABELS = {
[MyEnum.ONE]: 'Label one',
[MyEnum.TWO]: 'Label two'
}
// to declare type is important - otherwise TS complains on LABELS[type]
// also, if replace Object.values with Object.keys -
// - TS blames wrong types here: "string[] is not assignable to MyEnum[]"
const allKeys: Array<MyEnum> = Object.values(MyEnum)
const allowedKeys = allKeys.filter(
(type) => type !== MyEnum.ONE
)
const allowedLabels = allowedKeys.map((type) => ({
label: LABELS[type]
}))
虽然答案已经提供了,但几乎没有人指向文档
下面是一个片段
enum Enum {
A
}
let nameOfA = Enum[Enum.A]; // "A"
请记住,string enum成员根本不会生成反向映射。
假设您有一个枚举
export enum SCROLL_LABEL_OFFSET {
SMALL = 48,
REGULAR = 60,
LARGE = 112
}
你想要创建一个基于枚举的类型而不仅仅是复制和粘贴。 你可以像这样使用枚举来创建你的类型:
export type ScrollLabelOffset = keyof typeof SCROLL_LABEL_OFFSET;
结果你会收到一个可能值为'SMALL' | 'REGULAR' | 'LARGE'的类型