Enums 如何获取枚举项的名称?
我想迭代一个类型脚本一个Enums 如何获取枚举项的名称?,enums,typescript,Enums,Typescript,我想迭代一个类型脚本一个enum类型,并获得每个枚举符号名,例如: enum myEnum { entry1, entry2 } for (var entry in myEnum) { // use entry's name here, e.g., "entry1" } 你发布的代码将起作用;它将打印出枚举的所有成员,包括枚举成员的值。例如,以下代码: enum myEnum { bar, foo } for (var enumMember in myEnum) { con
enum
类型,并获得每个枚举符号名,例如:
enum myEnum { entry1, entry2 }
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
你发布的代码将起作用;它将打印出枚举的所有成员,包括枚举成员的值。例如,以下代码:
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 = parseInt(enumMember, 10) >= 0
if (isValueProperty) {
console.log("enum member: ", myEnum[enumMember]);
}
}
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",
}
这将只打印出名称:
Enum member: bar
Enum member: foo
警告:这稍微依赖于实现细节:TypeScript将枚举编译为JS对象,枚举值是该对象的成员。如果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,我使用类型化枚举:
export enum Option {
OPTION1 = <any>'this is option 1',
OPTION2 = <any>'this is option 2'
}
所以我必须通过键和值进行查询,并且只返回值:
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]]);
}
}
}
您可以使用我遇到相同问题时编写的
enum values
包:
我觉得这个解决方案更优雅:
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"
请记住,字符串枚举成员根本不会生成反向映射。如果只搜索名称并在以后迭代,请使用:
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开始,枚举将不再包含作为成员的键 需要注意的是,字符串初始化的枚举不能反向映射以获取原始枚举成员名称。换句话说,您不能通过编写颜色[“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
(,)为您完成这项工作,并提供许多额外的类型安全实用程序。适用于字符串和数字枚举,正确忽略数字枚举的数字索引反向查找项:
字符串枚举:
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;
}
stringVals
的类型是'entry1'|'entry2'
从TypeScript 2.4开始,枚举可以包含字符串初始化器 这允许您编写:
enum Order {
ONE = "First",
TWO = "Second"
}
console.log(`One is ${Order.ONE.toString()}`);
并获得以下输出:
一是第一
根据TypeScript文档,我们可以通过带有静态函数的枚举来实现这一点 使用静态函数获取枚举名称
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
有关使用静态函数枚举的更多信息,请访问以下链接
我的枚举如下:
for (var enumMember in myEnum) {
var isValueProperty = parseInt(enumMember, 10) >= 0
if (isValueProperty) {
console.log("enum member: ", myEnum[enumMember]);
}
}
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",
}
因此,执行此操作将返回未定义的:
为了解决此问题,我选择了另一种使用管道的方法:
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;
}
}
我编写了一个EnumUtil类,它通过enum值进行类型检查:
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'
}
如何使用它:
return this.enumKeyPipe.transform(UserSorting, [UserSorting.SortByUpdatedAt]);
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”、“B”]
StringValueEnumvalues的结果:[“A”、“B”]另一个有趣的解决方案是使用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']
]);
我通过搜索“TypeScript遍历枚举键”找到了这个问题。所以我只想发布一个在我的案例中对我有效的解决方案。也许这对某人也有帮助 我的例子如下:我想迭代每个枚举键,然后过滤一些键,然后访问一些对象,这些对象的键作为枚举中的计算值。这就是我在没有任何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 MyEnum={ONE='ONE',TWO='TWO'}
常量标签={
[MyEnum.ONE]:“标签一”,
[MyEnum.TWO]:“标签二”
}
//声明类型很重要-否则TS会在标签[type]上投诉
//此外,如果将Object.values替换为Object.keys-
//-TS在这里指责错误的类型:“字符串[]不可分配给MyEnum[]”
常量allKeys:Array=Object.values(MyEnum)
const allowedKeys=allKeys.filter(
(类型)=>类型!==MyEnum.ONE
)
const allowedLabels=allowedKeys.map((类型)=>({
标签:标签[类型]
}))
老问题,但是,为什么不使用常量
对象映射
而不是这样做:
enum Foo{
巴=60,
一切都很糟糕=80
}
console.log(Object.keys(Foo))
//->[“60”,“80”,“酒吧”,“一切都很糟糕”]
console.log(Object.values(Foo))
//->[“酒吧”,“一切都很糟糕”,60,80]
执行此操作(注意as const
强制转换):
const Foo={
酒吧:60,
一切都很糟糕:80
}常量
console.log(Object.keys(Foo))
//->[“酒吧”,“一切都很糟糕”]
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;
}
静态getEnumValues(enumType:{}):T[]{
常量值:T[]=[];
常量键=Object.keys(枚举类型);
for(键的常量键。切片(0,键的长度/2)){
值。按(+键);
}
返回值;
}
用法:
enum myEnum { entry1, entry2 };
const stringVals = getStringValuesFromEnum(myEnum);
for (const enumValue of getEnumValues<myEnum>(myEnum)) {
// do the thing
}
for(getEnumValues(myEnum)的常量enumValue){
//做那件事
}
该函数返回易于枚举的内容,并且还强制转换为枚举类型。如果您有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,您可以使用类似这些函数将枚举映射到rec
for (const enumValue of getEnumValues<myEnum>(myEnum)) {
// do the thing
}
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
});
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
}
}
enum AnimalEnum {
dog = "dog", cat = "cat", mouse = "mouse"
}
AnimalEnum["dog" as keyof typeof AnimalEnum]
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" To get the list of the enum values you have to use:
enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}
Object.values(AnimalEnum);
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)
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"]
const enumNames: string[] = Object.keys(YourEnum).filter(key => isNaN(Number(key)));