Enum conversions in TypeScript are a bit tricky. You can't be sure what will you receive when converting from your Enum. Let's take following enum as an example:
You will notice that generally converting from number gives a string and converting from string gives... number or string.
I was trying to solve a scenario where I had an unknown value (enum number value as a string or as a number or just an enum string value but I didn't know which one at the moment) and I needed to map it to the enum string value. I end up with below function. It's pretty generic because it can map any value to any enum.
enum Categories {When you take a look at the output of below conversions:
drawing = 1,
painting
}
var str: string = "painting";
var num: number = 2;
var numStr: string = "2";
var category: Categories = 2;
console.log(Categories[str]);
console.log(Categories[num]);
console.log(Categories[numStr]); //The most interesting case
console.log(Categories[category]);
You will notice that generally converting from number gives a string and converting from string gives... number or string.
I was trying to solve a scenario where I had an unknown value (enum number value as a string or as a number or just an enum string value but I didn't know which one at the moment) and I needed to map it to the enum string value. I end up with below function. It's pretty generic because it can map any value to any enum.
function varToEnumStringVal(value: any, enumerator: any): string {Usage:
var en: { [index: string]: any } = enumerator;
if (!isNaN(parseInt(value)))
return en[value];
var num = en[value];
return en[num];
}
var str: string = "painting";And now you can be sure that you will receive enum string value:
var num: number = 2;
var numStr: string = "2";
var category: Categories = 2;
console.log(varToEnumStringVal(str, Categories));
console.log(varToEnumStringVal(num, Categories));
console.log(varToEnumStringVal(numStr, Categories));
console.log(varToEnumStringVal(category, Categories));