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'.
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.
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.
The short answer is no, you can't extend enums because TypeScript offers no language feature to extend them.
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.
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.
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.
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:
If you want to get your
enum key
byvalue
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:
Another way: Retrieve enum key by value:
let enumKey = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];
console.log(enumKey);
Output:
Test on jsfiddle:
Coding sample on jsfiddle
Note: There are new annoucement published on 25th August
please be aware of it. Have alook here
const findMe = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];
https://jsfiddle.net/anniebbird/agy3unfk/3/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With