简体   繁体   中英

Typescript: How to get the enum "name" with its value?

I have this enum:

export enum myEnum {
  name1 = 'my name',
  name2 = 'my other name',
  name3 = 'other'
}

and i have a myEnum object:

const x = myEnum.name1;
console.log(x)  // prints 'my name' 

How can i print 'name1' with my const x? In other words, how to get the enum name 'name1' with a myEnum value 'myEnum.name1'?

EDIT:

This is how it looks:

在此处输入图片说明

在此处输入图片说明

As per the documentation , enums can be reverse-mapped as follows:

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

To enumerate the values and keys of the enum, it can effectively be treated as a standard JS object. Here, you might choose to probe it with Object.entries :

Object.entries(myEnum)

will yield an array of key-value pairs:

[["name1","my name"],["name2","my other name"],["name3","other"]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM