543

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"
}
yuvalm2
  • 742
  • 7
  • 23
CalvinDale
  • 7,657
  • 5
  • 24
  • 36
  • 1
    this tiny [enum-for](https://www.npmjs.com/package/enum-for) package has `getAllEnumValues` and `getAllEnumKeys` for your purpose – transang Jun 03 '20 at 16:34
  • 1
    I have created [a PR](https://github.com/microsoft/TypeScript/pull/42465) ([issue](https://github.com/microsoft/TypeScript/issues/42457)) to add native support for `for (const [name, value] of MyEnum) {` to Typescript. Hopefully this will be easier one day! – Timmmm Jan 26 '21 at 13:43
  • Must have been to difficult to provide a `EnumType.name()` method. – html_programmer Jan 12 '22 at 21:21
  • I found this article useful https://www.technicalfeeder.com/2021/07/mastering-enum-in-typescript/ – Etienne Jun 04 '22 at 07:15

41 Answers41

662

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

Here's a snippet

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

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

k.s.
  • 2,704
  • 1
  • 23
  • 25
shakram02
  • 8,982
  • 3
  • 20
  • 21
  • 3
    How about displaying `0` or `1` from this enum ? `export enum Octave { ZERO = 0, ONE = 1 }` – Stephane Jun 22 '19 at 20:31
  • @jbojcic Is it about situation: `enum Enum {"A"}; let nameOfA = Enum[Enum.A];`? As of typescript@2.9.2 it works fine for me... – ellockie Nov 26 '19 at 18:02
  • 3
    How about looping through values? – shioko May 08 '20 at 01:26
  • 1
    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 Feb 02 '21 at 12:31
  • 1
    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. – fgblomqvist Sep 30 '21 at 11:10
346

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 = parseInt(enumMember, 10) >= 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.

Alan
  • 845
  • 5
  • 22
Judah Gabriel Himango
  • 57,387
  • 37
  • 156
  • 207
  • 38
    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. – Judah Gabriel Himango May 11 '17 at 15:56
  • I think the `+enumMember >= 0` should be `isFinite(+enumMember)` because negative or floating point values get reverse mapped too. ([Playground](http://www.typescriptlang.org/play/?ts=3.1.6&ssl=5&ssc=65&pln=5&pc=51#code/KYOwrgtgBAsgngUXNA3gKCpqALYAbPAeygF4oBaARgCYBmAOmoBoMsB3QgJzwBNSoARB248BaAL5oAxoRABnQnmD0iAcwAUAeQBGAK2BSALvQDWwOHPXwkkAJS2oAekdQA2gNwFCApoKp1GH0FhXgEAXSA)) – spenceryue Nov 08 '19 at 19:23
  • Enum entries can be string with [leading zeros](https://www.typescriptlang.org/play?#code/KYOwrgtgBAwg9gGzgJygbwFBSs4ATKAXigEYAaLKAIgAYSqioAmDAXyA) like `00111`, you need to exclude these too – Austaras Nov 11 '20 at 09:13
  • As of TS 4, doesn't work with numeric and heterogenous enums. – polkovnikov.ph Mar 08 '21 at 16:11
106

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.

Michael Erickson
  • 3,759
  • 2
  • 19
  • 10
81

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[];
Simon
  • 1,083
  • 1
  • 11
  • 17
  • 24
    Or with the ES2017 lib: `Object.values(myEnum).filter(value => typeof value === 'string') as string[];` – None Mar 06 '18 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 Oct 16 '19 at 08:01
  • 2
    or just Object.values(myEnum).filter(isNaN) as string[]; – ihorbond Jun 20 '20 at 20:41
  • 1
    Isn't `Object.keys(myEnum)` enough to get an array with of key names in an enum object? – Bruno Negrão Zica Apr 04 '21 at 02:20
  • best way so far is `Object.entries(temp1).splice(Object.keys(temp1).length/2)` so we get the entries – jon Mar 22 '22 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']
Ryan Cavanaugh
  • 187,744
  • 51
  • 262
  • 230
  • **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 Nov 03 '17 at 09:04
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" ];
BenjaminJackman
  • 1,399
  • 1
  • 9
  • 18
Philip
  • 21,570
  • 2
  • 29
  • 31
  • 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 – Dima Karaush May 26 '21 at 07:41
31

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]
coyer
  • 3,607
  • 2
  • 26
  • 33
  • 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 – Shaung Cheng Apr 29 '20 at 05:49
  • 10
    Not so brilliant when the value is not the same as the key – Denny Oct 02 '20 at 13:22
  • This solution is good when you want to map enum values when passed a key, – kapil Dec 01 '20 at 12:55
30

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

wonea
  • 4,425
  • 17
  • 82
  • 137
John Huebner
  • 409
  • 4
  • 3
27

This solution work too.

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

var type: ScreenType = ScreenType.Edit;

console.log(ScreenType[type]); //Edit
Carlinhos
  • 832
  • 2
  • 9
  • 21
20

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)
AbolfazlR
  • 8,086
  • 4
  • 44
  • 60
  • 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. – polkovnikov.ph Mar 08 '21 at 16:15
  • @polkovnikov.ph- I updated my answer, in my opinion, you should not downvote a question because of the Writing error – AbolfazlR Mar 08 '21 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. – polkovnikov.ph Mar 08 '21 at 19:14
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();
Jeff Lau
  • 405
  • 4
  • 4
16

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
Flavien Volken
  • 16,172
  • 11
  • 86
  • 115
manzapanza
  • 5,774
  • 4
  • 37
  • 47
10

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;
};
wonea
  • 4,425
  • 17
  • 82
  • 137
kitko112
  • 658
  • 1
  • 7
  • 14
10

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.

polkovnikov.ph
  • 5,806
  • 4
  • 42
  • 74
10

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'

Volodymyr Khmil
  • 976
  • 13
  • 12
7

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

Git: enum-values

var names = EnumValues.getNames(myEnum);
Slava Shpitalny
  • 3,683
  • 2
  • 14
  • 21
  • 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 Aug 21 '17 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 Jun 21 '20 at 23:29
  • 1
    @jchook it will work. You can look at this [test](https://github.com/slavik57/enum-values/blob/9a1ef046e394f5f8b55f1be5e5d76070ae6591a3/src/enumValues.test.ts#L44) – Slava Shpitalny Jun 23 '20 at 06:07
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

Dmitry Efimenko
  • 10,679
  • 7
  • 63
  • 76
  • 1
    The function should return ```(keyof T)[]``` instead of ```keyof T```. Also, the ```export``` stops your playground from working. – Joald Aug 07 '18 at 08:12
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

wonea
  • 4,425
  • 17
  • 82
  • 137
Shahid Ahmad
  • 738
  • 1
  • 7
  • 15
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"]

asumaran
  • 987
  • 1
  • 8
  • 16
Arnold Vakaria
  • 189
  • 1
  • 9
6

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"
ASK
  • 348
  • 1
  • 4
  • 13
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
    }
}
user2080105
  • 1,483
  • 4
  • 16
  • 27
5

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]
    }))
wonea
  • 4,425
  • 17
  • 82
  • 137
Maksim Nesterenko
  • 4,863
  • 8
  • 49
  • 82
5

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'
Valentin Vignal
  • 3,144
  • 2
  • 16
  • 36
4

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]
Gabriel Rohden
  • 1,207
  • 9
  • 17
  • 1
    Correct me if im wrong but `console.log(Object.keys(Foo))` in the first example only returns `["BAR", "EVERYTHING_IS_TERRIBLE"]`.. – Peter Nov 08 '19 at 08:41
  • @Peter give a look [here at the ts playground](https://www.typescriptlang.org/play/#code/KYOwrgtgBAYg9nKBvAUFdUBCBBASlAXigDYAGAGjQwFEA1a3ATQBUAJASQDkBxAfXYDKvZg1ztMAGWqEoADlIoAvihQBjOCADOcADbAAdDrgBzABQB5AEYArYKoAu+gNbAAnptPw4ASm8ogA), just open the console and click on run. At least for me, it prints `["60", "80", "BAR", "EVERYTHING_IS_TERRIBLE"]` – Gabriel Rohden Nov 08 '19 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 Nov 11 '19 at 07:01
4

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
});
shoke
  • 6,278
  • 4
  • 36
  • 48
  • 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 Mar 11 '20 at 16:56
4

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

const enumNames: string[] = Object.keys(YourEnum).filter(key => isNaN(Number(key)));
Max Synyuk
  • 41
  • 3
3

I find that solution more elegant:

for (let val in myEnum ) {

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

It displays:

bar 
foo
Anthony Brenelière
  • 55,119
  • 14
  • 43
  • 55
3

Can be short and simple:

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

Object.keys(AnimalEnum).filter(v => typeof v == 'string' && isNaN(v))
Erisan Olasheni
  • 1,864
  • 13
  • 18
2

My Enum is like this:

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", 
}

so doing this return undefined:

UserSorting[UserSorting.SortByUpdatedAt]

To resolve this issue, I choose another way to do it using a Pipe:

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

And to use it:

return this.enumKeyPipe.transform(UserSorting, [UserSorting.SortByUpdatedAt]);
Cedric Arnould
  • 1,628
  • 2
  • 20
  • 44
2

To get the list of the enum values you have to use:

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

Object.values(AnimalEnum);
Radu Linu
  • 927
  • 8
  • 28
2

I hope the question is still relevant. I use such functions:

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

Example:

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"]
  • 1
    I'm using TS 3.7.1 and it gives TS errors for the parsedKeys and values vars. This can be fixed by typing out the values variable as `Array` and the parsedKeys variable as `string[]`. – Yulric Sequeira Jan 04 '21 at 13:03
  • @YulricSequeira Thank you! Updated types for variables' initialization. – Pavel Varentsov Jan 12 '21 at 07:54
  • `isNaN(parseInt(key)` is otherwise called `typeof key !== 'number'`. Convering a number to string and then back to number just to check that it's really a number is not smart. – polkovnikov.ph Mar 08 '21 at 16:13
  • @polkovnikov.ph Not quite so. `isNaN(parseInt(key)` gives more information, such as whether the string is a numeric string. – Pavel Varentsov Mar 10 '21 at 06:31
2

This would work more efficiently for key-value based 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
Bharath theorare
  • 488
  • 7
  • 27
2

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.

Vlad
  • 647
  • 1
  • 4
  • 9
1

I wrote a helper function to enumerate an enum:

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

Usage:

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

The function returns something that can be easily enumerated, and also casts to the enum type.

Russell Phillips
  • 699
  • 6
  • 11
1

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

A nice helper function:

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

// getAccountTypeName(AccountType.Twitter) === 'Twitter'
Chance
  • 10,647
  • 6
  • 56
  • 77
1

You can do the following, which I think is shortest, cleanest and fastest:

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

Given the following mixed type enum definition:

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

It will get transpire to the following:

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

After executing the function, you will get only the good entries:

[
  ["Critical", "critical"],
  ["Major", 3],
  ["Normal", "2"],
  ["Minor", "minor"],
  ["Info", "info"],
  ["Debug", 0]
] 
codenamezero
  • 2,431
  • 27
  • 56
0

Using a current version TypeScript you can use functions like these to map the Enum to a record of your choosing. Note that you cannot define string values with these functions as they look for keys with a value that is a number.

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
  }
}
geschwe1
  • 315
  • 3
  • 14
  • 1
    `.reduce((accum, key) => ({...accum, [key]: ... }), {})` is an antipattern with `O(N^2)` complexity. Don't use this code. – polkovnikov.ph Mar 08 '21 at 16:07
0

Quite a few answers here and considering I looked it up despite this being 7 years old question, I surmise many more will come here. Here's my solution, which is a bit simpler than other ones, it handles numeric-only/text-only/mixed value enums, all the same.

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)
 
AsG
  • 29
  • 5
0

If it's your enum and you define as seen below, names and values are the same, it'll give you the entries' names directly.

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

for (var entry in myEnum) { 
    // use entry's name here, e.g., "entry1"
}
Davut Gürbüz
  • 5,172
  • 4
  • 44
  • 80
0

Just to keep this question updated with all possible solutions , now we can use iterator protocol to make any object iterable

enum carsEnum{
  BMW="BMW",
  MERCEDES="Mercedes",
  TOYOTA="toyota",
}

carsEnum.[Symbol.iterator]=function(){
    let keys = Object.keys(carsEnum)
    let idx =0;
    return {
       next:()=>
         (idx<keys.length)?{value:this[keys[idx++]],done:false}:{value:undefined,done:true}
    } 
  }

for(let value of carsEnum){
  console.log(value) //'BMW' 'Mercedes'  'toyota'
}
M.abdelrhman
  • 686
  • 12
  • 22
-1

It is not exactly answer of your question but it is a trick to tackle your problem.

export module Gender {

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

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

}

You can extend your list model in a way you want.

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

Now, you can use it in this way:

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

or:

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