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

String Enums

Numeric enums can be nice when:

  • You actually want numbers
  • You really want to eke out every last bit of performance (numbers use less memory than strings)

But often, string enums are easier to work with if you just want labels.

enum LogLevel {
  ERROR = "ERROR",
  WARN = "WARN",
  INFO = "INFO",
  DEBUG = "DEBUG",
}

function structuredLog(message: string, level: LogLevel) {
  console.log(`[${level}] ${message}`);
}

structuredLog("User not found", LogLevel.ERROR);
// Outputs: [ERROR] User not found

When enums only exist within your code, numeric enums are totally fine. They start to get really hairy when you need to serialize them to JSON or store them in a database. There's nothing worse than debugging API responses and seeing this:

{
  "id": "94e83b65-ae9c-47f4-b788-d3f4fd085067",
  "name": "Lane",
  "user_type": 7 // what the h*ck is 7?!?!?
}

Assignment

It's hard to tell the severity of a request record in the Support.ai database, because it's just a number. Let's convert them to more readable strings.

    • It should take an old severity number value and return the corresponding RequestSeverity string value.
    • If the given severity number doesn't match one of the labels, it should throw a new error with the message: "Unknown severity"

Tip

When an enum is not given a value, it starts at 0 and auto-increments from there.