Typescript enum with multiple string values
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
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
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
}