The answer given by @Tukkan was correct, but it lacked the specificity needed. Below is a functional code snippet that directly addresses the original poster's question.
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
Some Important Notes:
- The function receives the enum object as a parameter and extracts its name. This contrasts with Tukkan's approach which requires direct access to the literal enum object - something not always feasible for users like the OP.
The indexing [0]
may be omitted. Correction: This behavior depends on the tsconfig setting. I adapted it here to avoid compile-time warnings, though this might not be universally recommended.
- Properly typing the object passed to the function is crucial to prevent compile-time errors. Using 'any' may introduce vulnerabilities, so ensure the object strictly adheres to enum structure.
- If you alter the function to align with Tukkan’s method, the outcome differs as demonstrated here:
function showEnumName(theEnum) {
const enumName = Object.keys({ theEnum })
console.log(enumName)
}
showEnumName({ Options })
In this scenario, instead of "Options", the output reads "theEnum". As pointed out by Tukkan, this reveals the variable name holding the data rather than the desired enum name.
If you find this response helpful, kindly upvote @Tukkan's answer as well to credit his contribution. This solution was built upon his insights, and recognition should be shared.