Reputation: 20466
My enum:
enum VerificationStatus {
pending,
rejected,
verified
}
I am trying to print the enum in the following format:
console.log(myEnumtoString(VerificationStatus.pending))
should print the string
"VerificationStatus.pending"
I tried:
console.log(`${typeof VerificationStatus}.${VerificationStatus[VerificationStatus.pending]}`)
But I get this:
"object.pending"
Upvotes: 3
Views: 1010
Reputation: 10882
This could work, but it's a bit clumsy:
console.log(`${Object.keys({VerificationStatus})[0]}.${VerificationStatus[VerificationStatus.pending]}`)
TypeScript compiles enums into variables with values as properties and a map of value names and indexes.
It means the code above uses this internal knowledge to print the name of the variable the enum is compiled into. It's brittle and I wouldn't recommend to use it.
As far as TypeScript has no official way how to get the enum name, I would just print it explicitly:
console.log(`VerificationStatus.${VerificationStatus[VerificationStatus.pending]}`)
Upvotes: 0
Reputation: 25800
For this to work, you would need a transformer like ts-nameof
.
Usage:
nameof.full(VerificationStatus.pending); // "VerificationStatus.pending"
Upvotes: 0
Reputation: 324
define your enum like this
enum VerificationStatus {
pending='pending',
rejected='rejected',
verified='verified'
}
Upvotes: 1