We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Enum Compilation

Unlike most TypeScript features, enums generate additional JavaScript code at runtime. Let's see what happens when we compile this enum (we'll talk about how to compile manually later):

enum Class {
  Rogue,
  Mage,
  Warrior,
  Priest,
}

We get a JavaScript object that looks like this:

var Class;
(function (Class) {
  Class[(Class["Rogue"] = 0)] = "Rogue";
  Class[(Class["Mage"] = 1)] = "Mage";
  Class[(Class["Warrior"] = 2)] = "Warrior";
  Class[(Class["Priest"] = 3)] = "Priest";
})(Class || (Class = {}));

This generated code creates the bidirectional mapping that we talked about before:

  • From name to value: Class["Rogue"] = 0
  • From value to name: Class[0] = "Rogue"

String Enum Compilation

Strings compile in a similar way:

enum Class {
  Rogue = "Rogue",
  Mage = "Mage",
  Warrior = "Warrior",
  Priest = "Priest",
}

Compiles to:

var Class;
(function (Class) {
  Class["Rogue"] = "Rogue";
  Class["Mage"] = "Mage";
  Class["Warrior"] = "Warrior";
  Class["Priest"] = "Priest";
})(Class || (Class = {}));

String enums do not support reverse mapping - the compiled JavaScript only maps from name to string value, not the other way around.

Assignment

Support.ai uses custom numeric error codes to track different kinds of internal errors. These codes are logged across systems, but for debugging, we want to display more information about the error.

  • Create and export a new function named getErrorLabel. It should take an error code number as input and return a string.
  • It should use reverse mapping on the InternalErrors enum to get the error name and return a string in this format:
    CODE: NAME
    With CODE and NAME replaced by the actual error code and error name.
  • If the given error code is not a value on the InternalErrors enum, it should return in the same format but with the error name "Unknown error".