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"
}