So I have this in the javascript for my page:
var TEST_ERROR = {
\'SUCCESS\' : 0,
\'FAIL\' : -1,
\'ID_ERROR\' : -2
For TypeScript, there is a simpler solution (Please ignore my answer if you stick with JS):
export enum Direction {
none,
left = 1,
right = 2,
top = 4,
bottom = 8
}
export namespace Direction {
export function toString(dir: Direction): string {
return Direction[dir];
}
export function fromString(dir: string): Direction {
return (Direction as any)[dir];
}
}
console.log("Direction.toString(Direction.top) = " + Direction.toString(Direction.top));
// Direction.toString(Direction.top) = top
console.log('Direction.fromString("top") = ' + Direction.fromString("top"));
// Direction.fromString("top") = 4
console.log('Direction.fromString("xxx") = ' + Direction.fromString("unknown"));
// Direction.fromString("xxx") = undefined
Because the enumeration type is compiled into an object(dictionary). You don't need a loop to find the corresponding value.
enum Direction {
left,
right
}
is compiled into:
{
left: 0
right: 1
0: "left",
1: "right"
}
This might be different from what you want but I want to share my answer. This was inspired by @LukeHconst solution. Consider bookCategory
below you will notice that I'm using a number as a key.
const bookCategory = {
"0": "Biography",
"1": "Fiction",
"2": "History",
"3": "Mystery",
"4": "Suspense",
"5": "Thriller"
};
I wrote the bookCategory
like this because if you are using an enum column in MySQL. For example,
category ENUM ('0', '1', '2', '3', '4', '5')
You would need some kind of conversion in JavaScript. So I came up with this and the usage is simple as:
bookCategory[book.category]
Building on Victor's excellent answer, so it works in TypeScript:
enumToStr(enumeration: any, value: any): string {
for (var k in enumeration)
if (enumeration[k] == value)
return <string>k;
return null;
}
Not quite optimal, but the cleanest you can get without pre-computing the reverse dictionary (and besides, this shouldn't be too much of an issue if you only have a few enumeration values):
function string_of_enum(enum,value)
{
for (var k in enum) if (enum[k] == value) return k;
return null;
}
Do you actually need the numeric values at all? If not then you could use something like this:
var TEST_ERROR = {
SUCCESS : 'Success',
FAIL : 'Fail',
ID_ERROR : 'ID Error'
};
You could always have the values be objects of a particular type.
var TEST_ERROR = (function() {
function ErrorValue(value, friendly) {
this.value = value;
this.friendly = friendly;
}
ErrorValue.prototype = {
toString: function() { return this.friendly; },
valueOf: function() { return this.value; }
};
return {
'SUCCESS': new ErrorValue(0, 'Success'),
'FAIL': new ErrorValue(1, 'Fail'),
'ID_ERROR': new ErrorValue(2, 'ID error')
};
})();
Now when you get a value of that type:
var err = testFunction(whatever);
you can get the string value with
alert(err.toString());
In fact you shouldn't even have to call .toString()
explicitly, most of the time.