24

I struggled find a way to get my enum variable name and the string part for the display name (to use both the variable name and string 'display' name)

I wanted this because I would use the variable name in my filter queries, and the display name to show on the front end.

So I found a way to create an object to act as an enum, and thought id just add it here for you guys.

3 Answers 3

28

Instead of creating an Interface or an Enum you can use a class with private constructor. And create static readonly instances of your class.

export class RewardCategory {
  public static readonly swapPoints = new RewardCategory('swapPoints', 'Swap Points');
  public static readonly charity = new RewardCategory('charity', 'Charity');
  public static readonly discountVouchers = new RewardCategory('discountVouchers', 'Discount Vouchers');

  private constructor(public readonly variable: string, public readonly displayName: string) {
  }
}

Then you could use it like this:

RewardCategory.charity.displayName

or

RewardCategory.charity.variable
Sign up to request clarification or add additional context in comments.

2 Comments

Upvoting this becuase it is easier to consume.
@AnishUnnikrishnan no, it is not. classes in typescript are heavy functions when they get compiled and passed around and even this piece of code is unneccesarily bloated and the recursion is confusing.
25

So Instead of creating an enum, just create an object in this format.

export const RewardCategory = { 
  swapPoints:  {variable: 'swapPoints', display: 'Swap Points' },
  charity: {variable: 'charity', display: 'Charity' },
  discountVouchers: {variable: 'discountVouchers', display: 'Discount Vouchers' }
}

Then, simply use it like this.

RewardCategory.swapPoints.display 

or

 RewardCategory.swapPoints.variable

1 Comment

I would use const instead of let. Also you can declare each RewardCategory value as EnumLayout (which shouldn't be named "enum"). Then, you can just use RewardCategory.swapPoints.display.
4

Enums are encoded as plain javascript objects so you can do the following:

enum Numbers {
    one = 'number one',
    two = 'the second number'
}

for (const key in Numbers)
    console.log(`key: ${key}, value: ${Numbers[key]}`);

function getTheKeyFromTheValue(value: string) {
    for (const key in Numbers)
        if (Numbers[key] === value)
            return key;

    return undefined; // Couldn't find it
}

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.