710

I would like to iterate a TypeScript enum object and get each enumerated symbol name, for example: enum myEnum { entry1, entry2 }

for (var entry in myEnum) { 
    // use entry's name here, e.g., "entry1"
}
4
  • 1
    this tiny enum-for package has getAllEnumValues and getAllEnumKeys for your purpose
    – Sang
    Commented Jun 3, 2020 at 16:34
  • 2
    I have created a PR (issue) to add native support for for (const [name, value] of MyEnum) { to Typescript. Hopefully this will be easier one day!
    – Timmmm
    Commented Jan 26, 2021 at 13:43
  • Must have been to difficult to provide a EnumType.name() method.
    – Trace
    Commented Jan 12, 2022 at 21:21
  • 1
    I found this article useful technicalfeeder.com/2021/07/mastering-enum-in-typescript
    – Etienne
    Commented Jun 4, 2022 at 7:15

44 Answers 44

861

Though the answer is already provided, Almost no one pointed to the docs

Here's a snippet

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

Keep in mind that string enum members do not get a reverse mapping generated at all.

8
  • 3
    How about displaying 0 or 1 from this enum ? export enum Octave { ZERO = 0, ONE = 1 }
    – Stephane
    Commented Jun 22, 2019 at 20:31
  • 3
    How about looping through values?
    – shioko
    Commented May 8, 2020 at 1:26
  • 4
    In JS enum is an object of [value]: name so you can get all values like that Object.keys(enum), all names Object.values(enum) and iterate in one go using for(const [value, name] of Object.entries(enum)) { ... }. Beware that when you get values they will be strings, not numbers as you would expect (since in JS keys of object are strings).
    – user0103
    Commented Feb 2, 2021 at 12:31
  • 5
    I don't see how this answers the question that was asked. Yes, the facts stated here are correct, and one could deduce an answer from it, but there is no direct answer. Commented Sep 30, 2021 at 11:10
  • 3
    Would be more clear if you name the enum something other than Enum
    – Hoppe
    Commented Aug 9, 2022 at 13:02
384

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 = Number(enumMember) >= 0
   if (isValueProperty) {
      console.log("enum member: ", myEnum[enumMember]);
   }
}

That will print out just the names:

Enum member: bar  
Enum member: 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.

4
  • 40
    To be clear, the above answer still works as of TS 2.3. However, if you use "const enum", rather than just "enum", only then will it not work. Using const enum is basically telling TS to do a search-and-replace; every place you use MyEnum.Foo, it will be replaced with a corresponding numeric value. Commented May 11, 2017 at 15:56
  • 1
    I think the +enumMember >= 0 should be isFinite(+enumMember) because negative or floating point values get reverse mapped too. (Playground)
    – spenceryue
    Commented Nov 8, 2019 at 19:23
  • 1
    Enum entries can be string with leading zeros like 00111, you need to exclude these too
    – Austaras
    Commented Nov 11, 2020 at 9:13
  • As of TS 4, doesn't work with numeric and heterogenous enums. Commented Mar 8, 2021 at 16:11
139

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.

2
  • 2
    This is a nice description of how TS enums work, but doesn't answer the question of how to "iterate" over "each enumerated symbol name". Commented Aug 19, 2022 at 21:37
  • Best example so far of how enums work! Thank you.
    – VPetrovic
    Commented Jul 3, 2023 at 8:53
105

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[];
7
  • 34
    Or with the ES2017 lib: Object.values(myEnum).filter(value => typeof value === 'string') as string[];
    – None
    Commented Mar 6, 2018 at 14:39
  • I needed to create a dict, and I used your answer as a startpoint. If someone else needs it, Object.values(myEnum).filter(value => typeof value === 'string').map(key => { return {id: myEnum[key], type: key }; });
    – Fejs
    Commented Oct 16, 2019 at 8:01
  • 3
    or just Object.values(myEnum).filter(isNaN) as string[];
    – ihor.eth
    Commented Jun 20, 2020 at 20:41
  • 2
    Isn't Object.keys(myEnum) enough to get an array with of key names in an enum object? Commented Apr 4, 2021 at 2:20
  • best way so far is Object.entries(temp1).splice(Object.keys(temp1).length/2) so we get the entries
    – jon
    Commented Mar 22, 2022 at 10:09
64

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']
2
  • Warning In modern typescript (tsc 2.5.2 atm) you are not even allowed to have a numeric string as a key to begin with. As such Himango's answer is better, since it covers all cases and has no downsides.
    – srcspider
    Commented Nov 3, 2017 at 9:04
  • Object.prototype.foo = 1; Commented Aug 19, 2022 at 21:54
52

It seems that none of the answers here will work with string-enums in strict-mode.

Consider enum as:

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

Accessing this with AnimalEnum["dog"] may result in an error like:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof AnimalEnum'.ts(7053).

Proper solution for that case, write it as:

AnimalEnum["dog" as keyof typeof AnimalEnum]
5
  • Brilliant solution for using the keyof with typeof! Other solution seems pretty opaque, but after all I think Typescript needs to keep improve on DX - Developer Experience for Enum
    – Shawn
    Commented Apr 29, 2020 at 5:49
  • 20
    Not so brilliant when the value is not the same as the key
    – Denny
    Commented Oct 2, 2020 at 13:22
  • This solution is good when you want to map enum values when passed a key,
    – kapil
    Commented Dec 1, 2020 at 12:55
  • This solution was so minimal, yet worked perfectly for my purposes. Excellent work! I used this in a map function for an api response. Much simpler than iterating though the object values or keys and working back from there. Very much appreciated!
    – BondAddict
    Commented Mar 23, 2023 at 15:44
  • This is what I was looking for, thanks!
    – times29
    Commented Sep 25, 2023 at 12:19
33

As of TypeScript 2.4, enums can contain string intializers 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

1
  • 2
    How does it "iterate" over "each enumerated symbol name"? This is not an answer to the given question at all. Commented Aug 19, 2022 at 21:33
32

With current TypeScript Version 1.8.9 I use typed Enums:

export enum Option {
    OPTION1 = <any>'this is option 1',
    OPTION2 = <any>'this is option 2'
}

with results in this Javascript object:

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" ];
3
  • well, code says different thing, you will get: optionNames = [["OPTION1", "this is option 1"], ["OPTION2", "this is option 2"]], but overall I appreciate your idea of removing double reversed entries, everyone else here considers that value is always a number Commented May 26, 2021 at 7:41
  • @DimaKaraush Not everyone. Also this answer relies on order of keys in objects, and is blatantly wrong. Commented Jun 16, 2022 at 0:03
  • After fixing issues with the code, it produces [["OPTION1", "this is option 1"], ["OPTION2", "this is option 2"]] instead. Even if you take first element of each of those tuples, it fails on enum Test2 { A, B } by producing ["0", "1", "A", "B"]. Commented Aug 19, 2022 at 22:02
30

This solution work too.

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

var type: ScreenType = ScreenType.Edit;

console.log(ScreenType[type]); //Edit
3
  • 2
    Why it prints 'undefined' for me? Any idea?
    – itsji10dra
    Commented May 4, 2021 at 11:06
  • 1
    How does it "iterate" over "each enumerated symbol name"? This is not an answer to the given question at all. Commented Aug 19, 2022 at 21:31
  • While you show how to access enums with its array accessor, I recommend adding the iteration part to answer the question
    – DerStoffel
    Commented Aug 20, 2022 at 11:07
28

In a nutshell

if your enums is as below:

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

to get specific text and value:

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

to get list of value and text:

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)

if your enums is as below:

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

to get specific text and value:

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

to get list of value and text:

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)
3
  • 4
    Doesn't work with string and heterogenous enums. By the look of thsi it's easy to imply the code wasn't ever compiled. Commented Mar 8, 2021 at 16:15
  • @polkovnikov.ph- I updated my answer, in my opinion, you should not downvote a question because of the Writing error Commented Mar 8, 2021 at 18:44
  • 2
    I downvoted it, because it's wrong. Numeric enums are not the only type of enums. Also I don't see why numbers have to be non-negative. enum A { B = -1 } is perfectly valid. Commented Mar 8, 2021 at 19:14
18

Another interesting solution found here is using 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']
]);

USE

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    
3
  • 4
    The question asked how to "iterate" over enum's keys. This doesn't answer the question. Commented Aug 19, 2022 at 22:05
  • 1
    I added an example showing how to iterate the map
    – manzapanza
    Commented Aug 20, 2022 at 17:09
  • Unfortunately, it's wrong. enum Test { A = 0 } Commented Aug 21, 2022 at 11:54
16

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:

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();
4
  • Looks bugged. Code doesn't distinguish between "0" and 0. Also, size of the library is ridiculous. Commented Jun 15, 2022 at 23:56
  • @polkovnikov.ph - Could you give more detail or an example of where the code fails to distinguish between "0" and 0? And about the size of the library, are you just looking at the total size of the NPM package? The size of the raw code itself is pretty small. Most of the package size is documentation (code comments and markdown files), and the fully documented source code is included with source maps for debugging.
    – Jeff Lau
    Commented Jun 17, 2022 at 14:51
  • For enum Test { NaN = 'LOL' } it produces []. Commented Aug 19, 2022 at 22:36
  • Also it takes over 1700 lines of code for something that should take 5. Commented Aug 19, 2022 at 22:37
16

I got tired looking through incorrect answers, and did it myself.

  • THIS ONE HAS TESTS.
  • Works with all types of enumerations.
  • Correctly typed.
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"]

Online version.

0
15

In TypeScript, an enum is compiled to a map (to get the value from the key) in javascript:

enum MyEnum {
  entry0,
  entry1,
}

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

It also creates a reversed map (to get the key from the value):

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

So you can access the name of an entry by doing:

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

However, string enum has no reverse map by design (see comment and pull request) because this could lead to conflict between keys and values in the map object.

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

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

If you want to force your string enum to compile a reversed map (you then have to make sure all the keys and values are different), you can use this trick:

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'
2
  • 1
    Nicely covered theory! The question asked for "get each enumerated symbol name" though. Commented Aug 19, 2022 at 22:42
  • JavaScript maps use .get() not [] notation to lookup a value, so are you sure it's a map? Commented May 22 at 9:18
13

Assume you have an enum

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

and you want to create a type based on enum but not just copy and paste. You could use an enum to create your type like this:

export type ScrollLabelOffset = keyof typeof SCROLL_LABEL_OFFSET;

In result you will receive a type with possible values as 'SMALL' | 'REGULAR' | 'LARGE'

1
  • 1
    But the question asked for a value, not for a type. Commented Aug 19, 2022 at 22:38
9

Starting from TypeScript 2.4, the enum would not contain the key as a member anymore. source from TypeScript readme

The caveat is that string-initialized enums can't be reverse-mapped to get the original enum member name. In other words, you can't write Colors["RED"] to get the string "Red".

My solution:

export const getColourKey = (value: string ) => {
    let colourKey = '';
    for (const key in ColourEnum) {
        if (value === ColourEnum[key]) {
            colourKey = key;
            break;
        }
    }
    return colourKey;
};
1
  • 2
    Question asked for "get each enumerated symbol name". This finds a specific key by value. Commented Aug 19, 2022 at 22:40
7

Based on some answers above I came up with this type-safe function signature:

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

Usage:

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

the type of stringVals is 'entry1' | 'entry2'

See it in action

2
  • 1
    The function should return (keyof T)[] instead of keyof T. Also, the export stops your playground from working.
    – Joald
    Commented Aug 7, 2018 at 8:12
  • For enum Test1 { A = "C", B = "D" } returns []. Commented Aug 19, 2022 at 22:44
7

They have provided a concept called 'reverse-mapping' in their official documentation. It helped me:

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

The solution is quite straight forward:

enum Enum {
 A,
}

let a = Enum.A;
let nameOfA = Enum[a]; // "A"
2
  • This works, but only on numeric enums. Commented Oct 1, 2021 at 20:31
  • 1
    Question asked for "get each enumerated symbol name". Commented Aug 19, 2022 at 22:46
6

According to TypeScript documentation, we can do this via Enum with static functions.

Get Enum Name with static functions

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 reading more about Enum with static function follow the below link https://basarat.gitbooks.io/typescript/docs/enums.html

1
  • This searches for enum key by value. Question asked for "get each enumerated symbol name". Commented Aug 19, 2022 at 22:55
6

I wrote an EnumUtil class which is making a type check by the enum value:

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

How to use it:

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

Result for NumberValueEnum keys: ["A", "B"]

Result for NumberValueEnum values: [0, 1]

Result for StringValueEnumkeys: ["A", "B"]

Result for StringValueEnumvalues: ["A", "B"]

2
  • Nice! However, I would switch what you define as keys and values. Values should be what's to the right of the equals sign, keys on the left
    – mwieczorek
    Commented Aug 20, 2020 at 16:15
  • How to use with heterogenous enums? Commented Mar 8, 2021 at 16:17
6

Having numeric enum:

enum MyNumericEnum {
 First = 1,
 Second = 2
}

You need to convert it to array first:

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

As you see, it contains both keys and values. Keys go first.

After that, you can retrieve its keys:

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

And values:

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

For string enums, you can use Object.keys(MyStringEnum) in order to get keys and Object.values(MyStringEnum) in order to get values respectively.

Though it's somewhat challenging to extract keys and values of mixed enum.

3
  • For numeric enum enum Test { A = 0, B = -1 } it produces ["A", 0] as keys. Commented Aug 19, 2022 at 23:08
  • Yes, having negative value seems to break the usual order. In this case slice operation won't work and some sort of filtering has to be applied (may include regexp).
    – Vlad
    Commented Aug 30, 2022 at 7:31
  • Having your example, it would be something like this: const enumValues = Object.values(Test); const keys = enumValues.filter((value) => !(/^-?\d+$/.test(value))); const values = enumValues.filter((value) => /^-?\d+$/.test(value));
    – Vlad
    Commented Aug 30, 2022 at 7:43
6

There are already a lot of answers here but I figure I'll throw my solution onto the stack anyway.

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

For Clarity:

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

Reference for TypeScript Record

To iterate:

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

A nice helper function:

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

// getAccountTypeName(AccountType.Twitter) === 'Twitter'
3
  • How does it "reverse" enum Test8 { A = "A", B = "A" }? The question asked for a way to "get each enumerated symbol name", i.e. for a list of keys. Commented Aug 19, 2022 at 23:21
  • @polkovnikov.ph you're right, I didn't spell out how to iterate with Object.entries
    – Chance
    Commented Aug 20, 2022 at 15:26
  • I came here for the type: +1 for keyof typeof <ENUM>
    – Lothre1
    Commented Dec 9, 2022 at 14:21
5

The only solution that works for me in all cases (even if values are strings) is the following :

var enumToString = function(enumType, enumValue) {
    for (var enumMember in enumType) {
        if (enumType[enumMember]==enumValue) return enumMember
    }
}
1
  • 2
    This searches for enum key by value. Question asked for "get each enumerated symbol name". Commented Aug 19, 2022 at 22:55
5

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})
4

You can use the enum-values package I wrote when I had the same problem:

Git: enum-values

var names = EnumValues.getNames(myEnum);
7
  • 4
    You aren't really answering the question, it would be better to document your answer with code/etc but I did find the package useful.
    – lucuma
    Commented Aug 21, 2017 at 16:03
  • Looks like the magic line is Object.keys(e).filter(key => isNaN(+key)), which will not work with string enums, etc, right?
    – jchook
    Commented Jun 21, 2020 at 23:29
  • 1
    @jchook it will work. You can look at this test Commented Jun 23, 2020 at 6:07
  • No, you can't, because it's buggy: for enum Test { A = 0, B = NaN } it returns ["A", "B", "NaN"]. Commented Aug 19, 2022 at 22:54
  • @polkovnikov.ph Yes this is an edge case, but not an interesting one. Who will ever define an enum like this? It is like arguing to not use '+' for adding numbers because when you pass it a string it concatenates instead of adding. As I see enums are keys mapped to either a string or a number. If you map it to a NaN, you are doing something wrong Commented Aug 21, 2022 at 18:45
4

I found this question by searching "TypeScript iterate over enum keys". So I just want to post solution which works for me in my case. Maybe it'll help to someone too.

My case is the following: I want to iterate over each enum key, then filter some keys, then access some object which has keys as computed values from enum. So this is how I do it without having any TS error.

    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]
    }))
0
4

You can get an array of names from Enum in this way:

const enumNames: string[] = Object.keys(YourEnum).filter(key => isNaN(Number(key)));
1
  • For enum Test { A = 0, B = NaN } it returns ["A", "B", "NaN"]. Commented Aug 19, 2022 at 23:00
4

In case if you want to get the name in the html

For this enum

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

Assign a variable in your component as

canadianProvinces = CanadianProvinces 

Then, in your html

{{canadianProvinces[0]}}
1
  • wicked sorcery!
    – Korayem
    Commented Nov 17, 2022 at 1:24
3

Old question, but, why do not use a const object map?

Instead of doing this:

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]

Do this (pay attention to the as const cast):

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]
4
  • 1
    Correct me if im wrong but console.log(Object.keys(Foo)) in the first example only returns ["BAR", "EVERYTHING_IS_TERRIBLE"]..
    – Peter
    Commented Nov 8, 2019 at 8:41
  • @Peter give a look here at the ts playground, just open the console and click on run. At least for me, it prints ["60", "80", "BAR", "EVERYTHING_IS_TERRIBLE"] Commented Nov 8, 2019 at 12:53
  • 1
    it seems your right, the fun thing if you change from numbers to strings you get the output i expected, i have no idea why typescript handles string and numbers differently in enums..
    – Peter
    Commented Nov 11, 2019 at 7:01
  • Because the question asks specifically for a way to iterate over enum? Commented Aug 19, 2022 at 22:57
3

If you have enum

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

Then you can get key and values like:

Object.keys(Diet).forEach((d: Diet) => {
  console.log(d); // KETO
  console.log(Diet[d]) // Ketogenic
});
2
  • 1
    This causes an error: Argument of type '(d: Diet) => void' is not assignable to parameter of type '(value: string, index: number, array: string[]) => void'. Types of parameters 'd' and 'value' are incompatible. Type 'string' is not assignable to type 'MyEnum'.(2345)
    – jrheling
    Commented Mar 11, 2020 at 16:56
  • For enum Test2 { A, B } it shows "0", "1", "A", "B" as keys. Commented Aug 19, 2022 at 22:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.