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?
const enumin your example. Your code doesn't work for non-constenums either. I'm not even sure what you expect if someone callsconverter(MyEnum2.BLACK), which has no analog inMyEnum1. Do you want it to throw an error? And sinceconst enums are not emitted to JavaScript, there's noMyEnum1orMyEnum2objects 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 ofconverter()is supposed to be.