1

I have two string enums that I'm trying to convert, one to the other, via value. The enum that I'm trying to get is a const string enum. Since it is const I'm failing to get it.

i.e.:

const enum MyEnum1 {
     ORANGE = 'orange',
     YELLOW = 'yellow'
}
enum MyEnum2 {
     ORANGE = 'orange',
     BLACK = 'black',
     YELLOW = 'yellow',

}

function getEnumKeyByEnumValue<T extends {[index:string]:string}>(myEnum:T, enumValue:string):keyof T|null {
    let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue);
    return keys.length > 0 ? keys[0] : null;
}

function converter(type2: MyEnum2): MyEnum1 {
     const enumKey = getEnumKeyByEnumValue(MyEnum1, type2);
     if (!enumKey) {
          throw new Error('Key does not exist');
     }
    return MyEnum1[enumKey];
}

You can see this example in Typescript Playground at this link

For the converter function I'm getting an error in the last line. I've tried the approaches that relate to non const enum and they only work for non const enum. If enum is defined as const it does not work.

How can it be done?

9
  • What is a "non-const enum"? It does not make any sense Commented Sep 14, 2021 at 16:17
  • 2
    I don't see a const enum in your example. Your code doesn't work for non-const enums either. I'm not even sure what you expect if someone calls converter(MyEnum2.BLACK), which has no analog in MyEnum1. Do you want it to throw an error? And since const enums are not emitted to JavaScript, there's no MyEnum1 or MyEnum2 objects to iterate through, so maybe what you want is impossible. In any case I urge you to provide a minimal reproducible example and describe exactly what error you are getting and what the expected input/output relationship of converter() is supposed to be. Commented Sep 14, 2021 at 18:57
  • @Nikita Ivanov, I've fixed the example. It was missing the const word. Commented Sep 15, 2021 at 7:20
  • @jcalz, see above comment. added a playground link. If you cannot help then thanks anyway for the effort in assisting. Alternative solutions are also good except ones that remove the const word from the enum as we generate it automatically in my company. Commented Sep 15, 2021 at 7:21
  • 2
    Does this answer your question? "TypeScript: Get member name of const enum as a string?", "Getting the enum key with the value string (reverse mapping) in TypeScript" Commented Sep 15, 2021 at 9:34

1 Answer 1

1

Seems to not be possible according to this answer:

https://stackoverflow.com/a/40227546/4884749

This question is in fact the same scenario described in the linked issue in other words.

const enums are fully erased during compilation which means that runtime evaluation is not possible

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.