Const enums are typically removed at compile time, meaning there is no runtime representation of the enum object. To preserve const enums and force the generation of the enum object, you can use preserveConstEnums
. However, even with this flag, accessing the enum object directly is not allowed by the compiler, requiring a workaround.
One approach with preserveConstEnums
enabled is to place the enum within a namespace:
namespace enums {
export const enum Snack {
Apple = 0,
Banana = 1,
Orange = 2,
Other = 3
}
}
let enumName = (enums as any).Snack[enums.Snack.Apple];
Alternatively, if the enum is part of a module:
export const enum Snack {
Apple = 0,
Banana = 1,
Orange = 2,
Other = 3
}
let enumName = (exports as any).Snack[Snack.Apple];
If you prefer not to use the flag, another workaround is to create an object that must include all enum members, allowing you to search for the name within it. This way, any additions or removals from the enum will prompt a compile-time error on the object:
let SnackNames: { [P in keyof typeof Snack]: { Name: P, Value: typeof Snack[P] } } = {
Apple: { Value: Snack.Apple, Name: "Apple" },
Banana: { Value: Snack.Banana, Name: "Banana" },
Orange: { Value: Snack.Orange, Name: "Orange" },
Other: { Value: Snack.Other, Name: "Other" },
}