TSR
TSR

Reputation: 20466

print enum as String typescript

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

Answers (3)

ttulka
ttulka

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

Karol Majewski
Karol Majewski

Reputation: 25800

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

Usage:

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

Upvotes: 0

Cereal_Killer
Cereal_Killer

Reputation: 324

define your enum like this

enum VerificationStatus {
    pending='pending', 
    rejected='rejected', 
    verified='verified'
}

Upvotes: 1

Related Questions