3

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"

3 Answers 3

1

define your enum like this

enum VerificationStatus {
    pending='pending', 
    rejected='rejected', 
    verified='verified'
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]}`)

Comments

0

For this to work, you would need a transformer like ts-nameof.

Usage:

nameof.full(VerificationStatus.pending); // "VerificationStatus.pending"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.