Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get enum key by value in Typescript?

I have an enum like this:

export enum Colors {
    RED = "RED COLOR",
    BLUE = "BLUE COLOR",
    GREEN = "GREEN COLOR"
}

Could you let me know how to get enum key by value please? i.e., I need to pass "BLUE COLOR" and get 'BLUE'.

Colors["BLUE COLOR"] gives error Element implicitly has an 'any' type because expression of type '"BLUE COLOR"' can't be used to index type 'typeof Colors'. Property 'BLUE COLOR' does not exist on type 'typeof Colors'.

like image 239
MAK Avatar asked Jun 05 '20 12:06

MAK


People also ask

What is enum key?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Should I use enum in TypeScript?

Enums in TypeScript are a very useful addition to the JavaScript language when used properly. They can help make it clear the intent of normally “magic values” (strings or numbers) that may exist in an application and give a type-safe view of them.

Can enum extend another enum TypeScript?

The short answer is no, you can't extend enums because TypeScript offers no language feature to extend them.

How to get the name of an enum in typescript?

In typescript we can have string enums as well. In this case we can directly get names of enum by looping string enum object. Why because string enums directly store key value pairs in enum object. To get the values of enum entries we can use name keys of enum object as shown below.

How do I get the value of an enum value?

Use the Object.values () method to get an array of the enum's values. Use the indexOf () method to get the index of the value in the array. Use the Object.keys () method to get an array of the enum's keys. Access the array of keys at the specific index.

How do I create an enum in JavaScript?

While the keys must be strings, as with JavaScript objects in general, the values for enum members are often auto-incremented numbers that mainly serve to distinguish one member from the other. Enums with only number values are called numeric enums. To create a numeric enum, use the enum keyword, followed by the name of the enum.

Why can’t I see the type of an enum object?

The reason for this error is that the CardinalDirection type represents a union type of all the enum members, not the type of the enum object itself. You can extract the object type by using typeof before the name of the enum. Check the highlighted code below:


3 Answers

If you want to get your enum key by value in that case you have to re write your enum in following manners: But same format also might be work in older version as well.

For Vanilla Js it should be like below:

 enum Colors {
    RED = "RED COLOR",
    BLUE = "BLUE COLOR",
    GREEN = "GREEN COLOR"
}

For .tsx it should be like below:

 enum Colors {
        RED = "RED COLOR" as any,
        BLUE = "BLUE COLOR" as any,
        GREEN = "GREEN COLOR" as any
    }

For .ts it should be like below:

enum Colors {
  RED = <any>"RED COLOR",
  BLUE = <any>"BLUE COLOR",
  GREEN = <any>"GREEN COLOR"
}

Then you can get like this way:

Retrieve enum key by value:

let enumKey = Colors["BLUE COLOR"];
    console.log(enumKey);

Output:

enter image description here

Another way: Retrieve enum key by value:

let enumKey = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];

console.log(enumKey);

Output:

enter image description here

Test on jsfiddle:

Coding sample on jsfiddle

Note: There are new annoucement published on 25th August please be aware of it. Have alook here

like image 169
Md Farid Uddin Kiron Avatar answered Oct 13 '22 14:10

Md Farid Uddin Kiron


const findMe = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];

https://jsfiddle.net/anniebbird/agy3unfk/3/

like image 37
Anna Avatar answered Oct 13 '22 12:10

Anna


I am using this function

export function getEnumKeyByEnumValue(myEnum: any, enumValue: number | string): string {
  let keys = Object.keys(myEnum).filter((x) => myEnum[x] == enumValue);
  return keys.length > 0 ? keys[0] : '';
}

Tests with jest

describe('enum', () => {
  enum TestEnumWithNumber {
    ZERO
  }

  enum TestEnumWithString {
    ZERO = 'ZERO'
  }

  it('should return correct key when enum has number values', function() {
    const key = getEnumKeyByEnumValue(TestEnumWithNumber, TestEnumWithNumber.ZERO);
    expect(key).toBe('ZERO');
  });

  it('should return correct key when enum has string values', function() {
    const key = getEnumKeyByEnumValue(TestEnumWithString, TestEnumWithString.ZERO);
    expect(key).toBe('ZERO');
  });

  it('should return correct key by passing corresponding string value', function() {
    const key = getEnumKeyByEnumValue(TestEnumWithString, 'ZERO');
    expect(key).toBe('ZERO');
  });
});

Hope it helps someone

like image 23
Nux Avatar answered Oct 13 '22 12:10

Nux