Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript enum with multiple string values

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.

like image 421
Ruan Avatar asked Sep 06 '18 09:09

Ruan


3 Answers

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
like image 141
Ruan Avatar answered Oct 10 '22 09:10

Ruan


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
like image 25
Falk Jäger Avatar answered Oct 10 '22 09:10

Falk Jäger


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
}
like image 24
Tom Cumming Avatar answered Oct 10 '22 08:10

Tom Cumming