Essentially, in JavaScript, enums
are represented as objects. When you define an enum
, you have the option to access the object in different ways.
If your keys include alphanumeric characters and spaces, you cannot access them using a dot notation after the enum name - for example, StatusCode.Ok 2
will result in an error.
In your scenario, you can access the object either by the assigned number or the assigned key. It's up to you to choose how to access it. You can access it like this: StatusCode['OK']
.
Here's an example to illustrate:
Source
/*
enum StatusCodes {
OK = 200,
BadRequest = 400,
Unauthorized,
PaymentRequired,
Forbidden,
NotFound
};
*/
// The above enum is converted to the Javasscript object like this.
var StatusCodes;
(function(StatusCodes) {
StatusCodes[StatusCodes["OK"] = 200] = "OK";
StatusCodes[StatusCodes["BadRequest"] = 400] = "BadRequest";
StatusCodes[StatusCodes["Unauthorized"] = 401] = "Unauthorized";
StatusCodes[StatusCodes["PaymentRequired"] = 402] = "PaymentRequired";
StatusCodes[StatusCodes["Forbidden"] = 403] = "Forbidden";
StatusCodes[StatusCodes["NotFound"] = 404] = "NotFound";
})(StatusCodes || (StatusCodes = {}));
// Ways to access the enum.
console.log(StatusCodes.OK);
console.log(StatusCodes["OK"]);
console.log(StatusCodes["200"]);