@Tukkan provided the right answer but it was too vague to use. Here is functional code that responds directly the OP.
enum Options {
yes,
no
}
type EnumType = Record<string, any>
function showEnumName(theEnum: EnumType) {
const enumName = Object.keys(theEnum)[0] ?? ''
console.log(enumName)
}
showEnumName({ Options })
Playground Link
Notes:
- The enum object is passed into the function, and the function derives the name from that object. Compare this to the inspirational response by Tukkan which requires that the process that gets the enum name must have the literal enum object - not a reference to it, which is what the OP and most of us needs.
The index [0]
isn't necessary. Corrected: This depends on tsconfig setting. I modified to avoid compile-time warning, which may or may not be good policy, but that's beyond the scope of this thread.
- Typing the object passed into the function is required to get this to work without compile-time errors. You can simply use (theEnum:any) but that would allow, um, anything in there. If you have a function that types the enum object as 'any' before passing it to this code, it's going to break. The object must be an enum. More rigorous typing is also beyond the scope of this thread.
- If you change the function to use syntax closer to what Tukkan suggested, here is what happens Playground :
function showEnumName(theEnum) {
const enumName = Object.keys({ theEnum })
console.log(enumName)
}
showEnumName({ Options })
The result is not "Options", it's "theEnum". That is, as Tukkan correctly noted, it's telling us the name of the variable that contains the data, which doesn't help inside the function when we want the name of the enum that was passed in.
If you like this Answer, please also upvote the answer by @Tukkan so that he gets points. This one would not have been possible without his. I cannot in good conscience take exclusive points when he provided the inspiration.