如何获得enum条目的名称?

我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}

.
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
756481 次浏览

你张贴的代码将工作;它将打印出枚举的所有成员,包括枚举成员的值。例如,以下代码:

enum myEnum { bar, foo }


for (var enumMember in myEnum) {
console.log("enum member: ", enumMember);
}

将打印以下内容:

Enum member: 0
Enum member: 1
Enum member: bar
Enum member: foo

如果你只想要成员名,而不是值,你可以这样做:

for (var enumMember in myEnum) {
var isValueProperty = Number(enumMember) >= 0
if (isValueProperty) {
console.log("enum member: ", myEnum[enumMember]);
}
}

只打印出名字:

Enum member: bar
Enum member: foo

注意:这有点依赖于实现细节:TypeScript将enum编译为JS对象,enum值是对象的成员。如果TS决定在未来以不同的方式实现它们,上述技术可能会中断。

假设您坚持使用规则,只生成带有数值的枚举,您可以使用这段代码。这正确地处理了名称恰好是有效数字的情况

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']

在当前的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" ];

当我遇到同样的问题时,你可以使用我写的enum-values包:

Git: enum-values

var names = EnumValues.getNames(myEnum);

我发现这个解决方案更优雅:

for (let val in myEnum ) {


if ( isNaN( parseInt( val )) )
console.log( val );
}

它显示:

bar
foo

对我来说,一个更简单、实用和直接的方法来理解正在发生的事情,就是下面的列举:

enum colors { red, green, blue };

本质上将转换为:

var colors = { red: 0, green: 1, blue: 2,
[0]: "red", [1]: "green", [2]: "blue" }

正因为如此,以下情况将是正确的:

colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0

这创建了一个简单的方法来获取枚举的名称,如下所示:

var color: colors = colors.red;
console.log("The color selected is " + colors[color]);

它还创建了一种将字符串转换为枚举值的好方法。

var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];

以上两种情况更为常见,因为通常您对特定值的名称和以通用方式序列化值更感兴趣。

虽然已经给出了答案,但几乎没有人指出文档

下面是一个片段

enum Enum {
A
}
let nameOfA = Enum[Enum.A]; // "A"

请记住,string enum成员根本不会生成反向映射。

如果你只搜索名称,然后迭代使用:

Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];

这个解决方案也可以。

enum ScreenType {
Edit = 1,
New = 2,
View = 4
}


var type: ScreenType = ScreenType.Edit;


console.log(ScreenType[type]); //Edit

唯一适用于我在所有情况下(即使值是字符串)的解决方案是:

var enumToString = function(enumType, enumValue) {
for (var enumMember in enumType) {
if (enumType[enumMember]==enumValue) return enumMember
}
}

从TypeScript 2.4开始,枚举不再包含键作为成员。# EYZ0

需要注意的是,字符串初始化的枚举不能反向映射到原始枚举成员名。换句话说,你不能写Colors["RED"]来获得字符串"RED"。

我的解决方案:

export const getColourKey = (value: string ) => {
let colourKey = '';
for (const key in ColourEnum) {
if (value === ColourEnum[key]) {
colourKey = key;
break;
}
}
return colourKey;
};

ts-enum-util (githubnpm)为您完成工作,并提供许多额外的类型安全实用程序。适用于字符串和数字enum,正确忽略数字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();

数字枚举:

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();

基于上面的一些回答,我提出了这个类型安全的函数签名:

export function getStringValuesFromEnum<T>(myEnum: T): (keyof T)[] {
return Object.keys(myEnum).filter(k => typeof (myEnum as any)[k] === 'number') as any;
}

用法:

enum myEnum { entry1, entry2 };
const stringVals = getStringValuesFromEnum(myEnum);

stringVals的类型是'entry1' | 'entry2'

See it in action

从TypeScript 2.4开始,枚举可以包含字符串初始化器https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html

这允许你这样写:

 enum Order {
ONE = "First",
TWO = "Second"
}


console.log(`One is ${Order.ONE.toString()}`);

得到这样的输出:

一个是First

根据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静态函数,请参见下面的链接 # EYZ0 < / p >

我的Enum是这样的:

export enum UserSorting {
SortByFullName = "Sort by FullName",
SortByLastname = "Sort by Lastame",
SortByEmail = "Sort by Email",
SortByRoleName = "Sort by Role",
SortByCreatedAt = "Sort by Creation date",
SortByCreatedBy = "Sort by Author",
SortByUpdatedAt = "Sort by Edit date",
SortByUpdatedBy = "Sort by Editor",
}

所以这样做返回未定义的:

UserSorting[UserSorting.SortByUpdatedAt]

为了解决这个问题,我选择了另一种使用管道的方法:

import { Pipe, PipeTransform } from '@angular/core';


@Pipe({
name: 'enumKey'
})
export class EnumKeyPipe implements PipeTransform {


transform(value, args: string[] = null): any {
let enumValue = args[0];
var keys = Object.keys(value);
var values = Object.values(value);
for (var i = 0; i < keys.length; i++) {
if (values[i] == enumValue) {
return keys[i];
}
}
return null;
}
}

要使用它:

return this.enumKeyPipe.transform(UserSorting, [UserSorting.SortByUpdatedAt]);

这不是你问题的确切答案,但它是解决你问题的一个技巧。

export module Gender {


export enum Type {
Female = 1,
Male = 2
};


export const List = Object.freeze([
Type[Type.Female] ,
Type[Type.Male]
]);


}

您可以以自己想要的方式扩展列表模型。

export const List = Object.freeze([
{ name: Type[Type.Female], value: Type.Female } ,
{ name: Type[Type.Male], value: Type.Male }
]);

现在,你可以这样使用它:

for(const gender of Gender.List){
console.log(gender.name);
console.log(gender.value);
}

或者:

if(i === Gender.Type.Male){
console.log("I am a man.");
}

我写了一个EnumUtil类,它通过枚举值进行类型检查:

export class EnumUtils {
/**
* Returns the enum keys
* @param enumObj enum object
* @param enumType the enum type
*/
static getEnumKeys(enumObj: any, enumType: EnumType): any[] {
return EnumUtils.getEnumValues(enumObj, enumType).map(value => enumObj[value]);
}


/**
* Returns the enum values
* @param enumObj enum object
* @param enumType the enum type
*/
static getEnumValues(enumObj: any, enumType: EnumType): any[] {
return Object.keys(enumObj).filter(key => typeof enumObj[key] === enumType);
}
}


export enum EnumType {
Number = 'number',
String = 'string'
}

如何使用:

enum NumberValueEnum{
A= 0,
B= 1
}


enum StringValueEnum{
A= 'A',
B= 'B'
}


EnumUtils.getEnumKeys(NumberValueEnum, EnumType.Number);
EnumUtils.getEnumValues(NumberValueEnum, EnumType.Number);


EnumUtils.getEnumKeys(StringValueEnum, EnumType.String);
EnumUtils.getEnumValues(StringValueEnum, EnumType.String);

NumberValueEnum键的结果:["A", "B"]

NumberValueEnum值的结果:[0,1]

StringValueEnumkeys的结果:["A", "

StringValueEnumvalues的结果:["A", "

另一个有趣的解决方案在这里找到是使用ES6 Map:

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']
]);

使用

console.log(TypeLabel.get(Type.low)); // Low Season




TypeLabel.forEach((label, value) => {
console.log(label, value);
});


// Low Season 0
// Mid Season 1
// High Season 2

我通过搜索“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]
}))

老问题,但是,为什么不使用const对象映射?

不要这样做:

enum Foo {
BAR = 60,
EVERYTHING_IS_TERRIBLE = 80
}


console.log(Object.keys(Foo))
// -> ["60", "80", "BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE", 60, 80]

这样做(注意as const类型):

const Foo = {
BAR: 60,
EVERYTHING_IS_TERRIBLE: 80
} as const


console.log(Object.keys(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> [60, 80]

我写了一个helper函数来枚举一个枚举:

static getEnumValues<T extends number>(enumType: {}): T[] {
const values: T[] = [];
const keys = Object.keys(enumType);
for (const key of keys.slice(0, keys.length / 2)) {
values.push(<T>+key);
}
return values;
}

用法:

for (const enumValue of getEnumValues<myEnum>(myEnum)) {
// do the thing
}

该函数返回可以轻松枚举的内容,并将其转换为枚举类型。

如果你有enum

enum Diet {
KETO = "Ketogenic",
ATKINS = "Atkins",
PALEO = "Paleo",
DGAF = "Whatever"
}

然后你可以得到如下的键和值:

Object.keys(Diet).forEach((d: Diet) => {
console.log(d); // KETO
console.log(Diet[d]) // Ketogenic
});

使用当前版本的TypeScript,你可以使用这些函数将Enum映射到你选择的记录。注意,不能用这些函数定义字符串值,因为它们查找值为数字的键。

enum STATES {
LOGIN,
LOGOUT,
}


export const enumToRecordWithKeys = <E extends any>(enumeration: E): E => (
Object.keys(enumeration)
.filter(key => typeof enumeration[key] === 'number')
.reduce((record, key) => ({...record, [key]: key }), {}) as E
);


export const enumToRecordWithValues = <E extends any>(enumeration: E): E => (
Object.keys(enumeration)
.filter(key => typeof enumeration[key] === 'number')
.reduce((record, key) => ({...record, [key]: enumeration[key] }), {}) as E
);


const states = enumToRecordWithKeys(STATES)
const statesWithIndex = enumToRecordWithValues(STATES)


console.log(JSON.stringify({
STATES,
states,
statesWithIndex,
}, null ,2));


// Console output:
{
"STATES": {
"0": "LOGIN",
"1": "LOGOUT",
"LOGIN": 0,
"LOGOUT": 1
},
"states": {
"LOGIN": "LOGIN",
"LOGOUT": "LOGOUT"
},
"statesWithIndex": {
"LOGIN": 0,
"LOGOUT": 1
}
}

这里的答案似乎都不能在strict-mode下使用string-enum。

考虑enum为:

enum AnimalEnum {
dog = "dog", cat = "cat", mouse = "mouse"
}

使用AnimalEnum["dog"]访问它可能会导致如下错误:

# EYZ0。

这种情况下的正确解,写为:

AnimalEnum["dog" as keyof typeof AnimalEnum]

这里已经有很多答案了,但我想我还是把我的解决方案扔到堆栈上。

<一个href = " https://www.typescriptlang.org/play/代码/ KYOwrgtgBAggxnA9mEAXAKgTwA7CgbwFgAoKKAcUUQHMAbPAXigHJqrmAaEsgGUTgCGtKE2aDanblABiAuMABGVANYiWSxJNJR0AdwCWqVMABOa5gdRbe + kMuAATAJIhzt5cxIBfEqhx4AaWBMNXtMRAAzKD9cSNgEZDQsXCgAelSoIJCmACJKGnocqAAfKBy + cSLSnNl5DWUqsr1DYxNG8vdHFxySJBAAZ1QobAF9E0c1AAoAeQUAK2A4VAA6MP7J + CQUDH8ASigBfszggG0AXV3l8YcweUnJuTgOKDD9hgA + AilHk83EndwJzCZzOoWCUnGqDAJlcj28z3wXgORwASotECYHAAeP7bZLAZ6DEy2ajvXYkCnEPqDKDUYCoXFJfwAOQEEEYUEmMWAAC54lsmbg3p8iNpIdDXCMxo4Ttyzt4ANyU3qIAaIejLWg0SZ0hkJPEstnADb6wXAZa1RQqXa7IA" rel="nofollow noreferrer">TypeScript Playground .

enum AccountType {
Google = 'goo',
Facebook = 'boo',
Twitter = 'wit',
}


type Key = keyof typeof AccountType // "Google" | "Facebook" | "Twitter"


// this creates a POJO of the enum "reversed" using TypeScript's Record utility
const reversed = (Object.keys(AccountType) as Key[]).reduce((acc, key) => {
acc[AccountType[key]] = key
return acc
}, {} as Record<AccountType, string>)

为了清晰:

/*
* reversed == {
*   "goo": "Google",
*   "boo": "Facebook",
*   "wit": "Twitter",
* }
* reversed[AccountType.Google] === "Google" 👍
*/

参考打字文件记录

迭代:

for (const [key, value] of Object.entries(reversed)) {
console.log(`${key}: ${value}`);
}

一个很好的帮助函数:

const getAccountTypeName = (type: AccountType) => {
return reversed[type]
};


// getAccountTypeName(AccountType.Twitter) === 'Twitter'

要获得枚举值的列表,您必须使用:

enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}


Object.values(AnimalEnum);

这里有很多答案,尽管这是一个7年前的问题,但我还是查了一下,我猜会有更多的答案出现在这里。这是我的解决方案,它比其他解决方案简单一点,它处理数字/文本/混合值枚举,都是一样的。

enum funky {
yum , tum='tum', gum = 'jump', plum = 4
}


const list1 = Object.keys(funky)
.filter(k => (Number(k).toString() === Number.NaN.toString()));
console.log(JSON.stringify(list1)); // ["yum","tum","gum","plum"]"


// for the numeric enum vals (like yum = 0, plum = 4), typescript adds val = key implicitly (0 = yum, 4 = plum)
// hence we need to filter out such numeric keys (0 or 4)
 

简单地说

如果你的enums如下所示:

export enum Colors1 {
Red = 1,
Green = 2,
Blue = 3
}

要获得特定的文本和值:

console.log(Colors1.Red); // 1
console.log(Colors1[Colors1.Red]); // Red

获取值和文本列表:

public getTextAndValues(e: { [s: number]: string }) {
for (const enumMember in e) {
if (parseInt(enumMember, 10) >= 0) {
console.log(e[enumMember]) // Value, such as 1,2,3
console.log(parseInt(enumMember, 10)) // Text, such as Red,Green,Blue
}
}
}
this.getTextAndValues(Colors1)

如果你的enums如下所示:

export enum Colors2 {
Red = "Red",
Green = "Green",
Blue = "Blue"
}

要获得特定的文本和值:

console.log(Colors2.Red); // Red
console.log(Colors2["Red"]); // Red

获取值和文本列表:

public getTextAndValues(e: { [s: string]: string }) {
for (const enumMember in e) {
console.log(e[enumMember]);// Value, such as Red,Green,Blue
console.log(enumMember); //  Text, such as Red,Green,Blue
}
}
this.getTextAndValues(Colors2)

我希望这个问题仍然有意义。我使用这样的函数:

function enumKeys(target: Record<string, number|string>): string[] {
const allKeys: string[] = Object.keys(target);
const parsedKeys: string[] = [];


for (const key of allKeys) {
const needToIgnore: boolean
= target[target[key]]?.toString() === key && !isNaN(parseInt(key));


if (!needToIgnore) {
parsedKeys.push(key);
}
}


return parsedKeys;
}


function enumValues(target: Record<string, number|string>): Array<string|number> {
const keys: string[] = enumKeys(target);
const values: Array<string|number> = [];


for (const key of keys) {
values.push(target[key]);
}


return values;
}

例子:

enum HttpStatus {
OK,
INTERNAL_ERROR,
FORBIDDEN = 'FORBIDDEN',
NOT_FOUND = 404,
BAD_GATEWAY = 'bad-gateway'
}




console.log(enumKeys(HttpStatus));
// > ["OK", "INTERNAL_ERROR", "FORBIDDEN", "NOT_FOUND", "BAD_GATEWAY"]


console.log(enumValues(HttpStatus));
// > [0, 1, "FORBIDDEN", 404, "bad-gateway"]

我看不正确的答案看累了,就自己做了。

  • 这个有测试。
  • 适用于所有类型的枚举。
  • 正确地输入。
type EnumKeys<Enum> = Exclude<keyof Enum, number>


const enumObject = <Enum extends Record<string, number | string>>(e: Enum) => {
const copy = {...e} as { [K in EnumKeys<Enum>]: Enum[K] };
Object.values(e).forEach(value => typeof value === 'number' && delete copy[value]);
return copy;
};


const enumKeys = <Enum extends Record<string, number | string>>(e: Enum) => {
return Object.keys(enumObject(e)) as EnumKeys<Enum>[];
};


const enumValues = <Enum extends Record<string, number | string>>(e: Enum) => {
return [...new Set(Object.values(enumObject(e)))] as Enum[EnumKeys<Enum>][];
};


enum Test1 { A = "C", B = "D"}
enum Test2 { A, B }
enum Test3 { A = 0, B = "C" }
enum Test4 { A = "0", B = "C" }
enum Test5 { undefined = "A" }
enum Test6 { A = "undefined" }
enum Test7 { A, B = "A" }
enum Test8 { A = "A", B = "A" }
enum Test9 { A = "B", B = "A" }


console.log(enumObject(Test1)); // {A: "C", B: "D"}
console.log(enumObject(Test2)); // {A: 0, B: 1}
console.log(enumObject(Test3)); // {A: 0, B: "C"}
console.log(enumObject(Test4)); // {A: "0", B: "C"}
console.log(enumObject(Test5)); // {undefined: "A"}
console.log(enumObject(Test6)); // {A: "undefined"}
console.log(enumObject(Test7)); // {A: 0,B: "A"}
console.log(enumObject(Test8)); // {A: "A", B: "A"}
console.log(enumObject(Test9)); // {A: "B", B: "A"}


console.log(enumKeys(Test1)); // ["A", "B"]
console.log(enumKeys(Test2)); // ["A", "B"]
console.log(enumKeys(Test3)); // ["A", "B"]
console.log(enumKeys(Test4)); // ["A", "B"]
console.log(enumKeys(Test5)); // ["undefined"]
console.log(enumKeys(Test6)); // ["A"]
console.log(enumKeys(Test7)); // ["A", "B"]
console.log(enumKeys(Test8)); // ["A", "B"]
console.log(enumKeys(Test9)); // ["A", "B"]


console.log(enumValues(Test1)); // ["C", "D"]
console.log(enumValues(Test2)); // [0, 1]
console.log(enumValues(Test3)); // [0, "C"]
console.log(enumValues(Test4)); // ["0", "C"]
console.log(enumValues(Test5)); // ["A"]
console.log(enumValues(Test6)); // ["undefined"]
console.log(enumValues(Test7)); // [0, "A"]
console.log(enumValues(Test8)); // ["A"]
console.log(enumValues(Test9)); // ["B", "A"]

<一个href = " https://www.typescriptlang.org/play?target=7代码/ C4TwDgpgBAogdgVwLYGkIgM4B57IHxQC8sAHgMYA2CAJhFgNboD2AZrIkgDRQcBGEAJzwAoYWSZwMwKBA4B5XgCsIZacRwcZJYLOoYoAJRVMB1LFIEBLOAHNufQVAA + UC9Zt48ACggAudsgAlEQEAN7CUJFQ4pLS4mAgRFChAHRpEAC + UACG + qFQANooUNYBqOjYuEh4ALr + VUU1UBkA3BFRCsqqKQBu2VQQGD6BKSwmMNlkABZefQMhUKCQrFBzCNCEm1AA5A4C21AAZIdQtBQQOtFMCQVrEDWBbVFQAhcIAnBXCW2tojFSMg4aEwSQ0yC0OjgekMxlM5mAVls9mQ-AEzlcCPcnh89Q4wUIYXakVewHen06KmAKUYmB88iUlOGwVyZWBlQ4eAKNR + bTEEgBsmQADV + ut9OoqhDdPojOI4W4kTwUY4XAqPN4-GV8YTniSyYU0ik4BAAO5QADKFy8FO6dyGgqQNuATMCTRZDSqbLB1RqXJ5ogdUAAKoNgABGZJQACCSQARABhWPcABCcYAIrGMsJAyGpAAmSNRlPNbOaXPAADMhaSAAZi8QE7GSznQwAWasNmtJqCphuJ5tl0MAVkjCChEBY1gg1DjUabWZbUgAbB2oLGx7RJ8bqPPS + DywB2Qv1tdzgf70MADlXsbnJ9vu8XwAAnDfk93e6fd3zJExzikKCYGw6WQJ0vHLMNAkeKAAHoYOSKN-EbFMkIzLN-j-CAAKAkDHQZVRwNDPMoJaWD4NCRCoDrHt-DDdD + Uw7DgIdMDywrEiyIQ-xqOTJDE3o39-0A5j6S6Z1y1bDi4K4tcuxQtd + J-DBGOE3DWOHKTyI3Ccp2oJC5wE5ShJwlj8PE0Ml00mT13HLdp0zJSVJM0TGUPKyKO4zheK-QynJE0CzMIqRL3cyiH3kh9fOM-y8LEoKX1CpD3wigy-gY6lclzeliog6scnctd3xqrymodlly2i3l4pyu9ctjyqmnkoekni9iqskaryykkqsnusqwokqy7s7jj3br0tt2vy7s7j3j0atqmnbjtpcsqpmzrusas7 +ou0Nn0OkbuvGvqOBFAYhggjbE24WMMxOvzcK+sV4sq0i8uosNgaa4VRUGVqhuoxs4fuz7EZ+ tsnrkhsxruiahtbj7hlw2ubdpqqaqzi2n4oombubndgicx774quqhqs21nqax +Lnuu5KvxqIA" rel="noreferrer">在线版本号

如果它是您的enum,并且如下所示定义,名称和值是相同的,它将直接为您提供条目的名称。

enum myEnum {
entry1="entry1",
entry2="entry2"
}


for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}

这对于基于键值的enum更有效:

enum yourEnum {
["First Key"] = "firstWordValue",
["Second Key"] = "secondWordValue"
}


Object.keys(yourEnum)[Object.values(yourEnum).findIndex(x => x === yourValue)]
// Result for passing values as yourValue
// FirstKey
// SecondKey

你可以用下面的方法从Enum中获取一个名称数组:

const enumNames: string[] = Object.keys(YourEnum).filter(key => isNaN(Number(key)));

他们在官方文件中提供了一个叫做“反向映射”的概念。它帮助了我:

https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings

解决方法很简单:

enum Enum {
A,
}


let a = Enum.A;
let nameOfA = Enum[a]; // "A"

假设您有一个enum

export enum SCROLL_LABEL_OFFSET {
SMALL = 48,
REGULAR = 60,
LARGE = 112
}

,你想创建一个基于枚举的类型,而不仅仅是复制和粘贴。 您可以使用enum来创建type,如下所示:

export type ScrollLabelOffset = keyof typeof SCROLL_LABEL_OFFSET;

结果,您将收到一个type,可能的值为'SMALL' | 'REGULAR' | 'LARGE'

可以是简短的:

enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}


Object.keys(AnimalEnum).filter(v => typeof v == 'string' && isNaN(v))

在TypeScript中,一个enum在javascript中被编译成一个map(从键中获取值):

enum MyEnum {
entry0,
entry1,
}


console.log(MyEnum['entry0']); // 0
console.log(MyEnum['entry1']); // 1

它还创建了一个反向映射(从值中获取键):

console.log(MyEnum[0]); // 'entry0'
console.log(MyEnum[0]); // 'entry1'

所以你可以通过以下方式访问一个条目的名称:

console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'

但是,字符串enum没有反向映射(参见评论把请求),因为这可能导致映射对象中的键和值之间的冲突。

enum MyEnum {
entry0 = 'value0',
entry1 = 'value1',
}


console.log(MyEnum['value0']); // undefined
console.log(MyEnum['value1']); // undefined

如果你想强制你的字符串enum编译一个反向映射(你必须确保所有的键和值都是不同的),你可以使用这个技巧:

enum MyEnum {
entry0 = <any>'value0',
entry1 = <any>'value1',
}


console.log(MyEnum['value0']); // 'entry0'
console.log(MyEnum['value1']); // 'entry1'
console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'

有# EYZ0:

enum MyNumericEnum {
First = 1,
Second = 2
}

你需要先把它转换成数组:

const values = Object.values(MyNumericEnum);
// ['First', 'Second', 1, 2]

如您所见,它同时包含键和值。钥匙先放。

之后,你可以检索它的键:

values.slice(0, values.length / 2);
// ['First', 'Second']

和值:

values.slice(values.length / 2);
// [1, 2]

对于字符串枚举,您可以使用Object.keys(MyStringEnum)来分别获取键和Object.values(MyStringEnum)来分别获取值。

尽管提取混合枚举的键和值有点困难。

你可以这样做,我认为这是最短、最干净、最快的:

Object.entries(test).filter(([key]) => (!~~key && key !== "0"))

给定以下混合类型枚举定义:

enum testEnum {
Critical = "critical",
Major = 3,
Normal = "2",
Minor = "minor",
Info = "info",
Debug = 0
};

它将会变成以下内容:

var testEnum = {
Critical: 'critical',
Major: 3,
Normal: "2",
Minor: 'minor',
Info: "info",
Debug: 0,
[0]: "critical",
[1]: 3,
[2]: "2",
[3]: "minor",
[4]: "info",
[5]: 0
}


function safeEnumEntries(test) {
return Object.entries(test).filter(([key]) => (!~~key && key !== "0"));
};


console.log(safeEnumEntries(testEnum));

执行函数后,你会得到只有项:

[
["Critical", "critical"],
["Major", 3],
["Normal", "2"],
["Minor", "minor"],
["Info", "info"],
["Debug", 0]
]

我的微薄的2美分是基于阅读github TS讨论的一个很棒的评论

const EnvironmentVariants = ['development', 'production', 'test'] as const
type EPredefinedEnvironment = typeof EnvironmentVariants[number]

然后在编译时:

// TS2322: Type '"qaEnv"' is not assignable to type '"development" | "production" | "test"'.
const qaEnv: EPredefinedEnvironment = 'qa'

在运行时:

function isPredefinedEnvironemt(env: string) {
for (const predefined of EnvironmentVariants) {
if (predefined === env) {
return true
}
}
return false
}


assert(isPredefinedEnvironemet('test'), true)
assert(isPredefinedEnvironemet('qa'), false)

注意,for(const index in EnvironmentVariants) {...}将遍历&;0&;,&;1&;,&;2&;集

<一个href = " https://www.typescriptlang.org/play?ssl=20& ssc = 1, pln = 21, pc = 1 #代码/ KYOwrgtgBAKgTgQxAZwQYwC4EsD2IDKGCGYyUA3gFBRT4CqAQgLICSMMAogCJQC8UAcmRgARhCwYMwACYCANNSgBBAAoqASgHkAatz6CEAB0NwcANxnzFKpSx78BhhFlkKaAYSUA5dxwAyfnoOaEhowAA24ZZuUFwc7n4sXkGC0sBo4Vgg0dZavvj4SQDi + o6mYcjIWQDmVgC + lI1RGFDIwBgAjPqaIgBW6RgAdKAYcFjAyAAU8EiomLgERCTIAJSDAGZY4VJwk5MA2nJmCOFgwAC6K3wAfFDHp8B8vPwzKOjYeITEpIP0zGycHgAHyBdxOZyeL0Qb3mnyWP08Pn8gS4awgRj2 + wA1sAAJ5yS43CiKGhwdpgOAgKA43GUOorRqUZqtdoAJm6fQGwxAo3GU1ecw + i2 + qw2wx2mko4iuv14t3ueoenm7wwx2wgxsdigilbd0hsghgrv8oqg1ug03drgionijstuvboppjlopelpdkz7sgj3cagk8wr +D1+phBjT+UbVXCRd7KGg8MgcFFBuEcNVJuQ2p05LnWXJ-UHcch6UA" rel="nofollow noreferrer">typescript playground example .

enum TransactionStatus {
SUBMITTED = 'submitted',
APPROVED = 'approved',
PAID = 'paid',
CANCELLED = 'cancelled',
DECLINED = 'declined',
PROCESSING = 'processing',
}




let set1 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.SUBMITTED || value === TransactionStatus.CANCELLED).map(([key,]) => {
return key
})




let set2 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.PAID || value === TransactionStatus.APPROVED).map(([key,]) => {
return key
})


let allKeys = Object.keys(TransactionStatus)






console.log({set1,set2,allKeys})

如果你想在html中获取名字

对于这个枚举

enum CanadianProvinces {
AB,
BC,
MB,
NB,
NL,
NT,
NS,
NU,
ON,
PE,
QC,
SK,
YT
}

将组件中的变量赋值为

canadianProvinces = CanadianProvinces

然后,在你的html

\{\{canadianProvinces[0]}}