TypeScript Course
TypeScript
/
Beginner

String Enums

Definition

Enums where each member must be explicitly initialized with a string literal, providing better readability at runtime than numeric enums.

Explain Like I'm New

If a numeric enum is a secret code (Admin = 1), a String Enum is a name tag (Admin = 'ADMIN'). When you look at the raw data in your database or logs, you don't see a random '1', you actually see the word 'ADMIN', which makes debugging much easier.

Real World Example

Defining strict API routes: `enum Routes { Login = '/auth/login', Dashboard = '/app/dashboard' }`.

Common Use Cases

  • •Debugging-friendly logs
  • •Database storage where exact strings are preferred over IDs

Interactive Example

enum Theme {
  Dark = "DARK_MODE",
  Light = "LIGHT_MODE",
  System = "SYSTEM_DEFAULT"
}

// In compiled JS, this looks like:
// var Theme;
// (function (Theme) {
//     Theme["Dark"] = "DARK_MODE";
// })(Theme || (Theme = {}));

const userPreference = Theme.Dark;
console.log(userPreference); // Output: "DARK_MODE" (Very readable!)

Interview Questions

basic

  • Do string enums auto-increment like numeric enums?

intermediate

  • Why are string enums easier to debug than numeric enums?

advanced

  • Do string enums support reverse mapping?

Flash Cards

Question

Do they auto-increment?

Click to reveal answer
Answer

No. Because they are strings, TypeScript cannot automatically 'add 1' to the previous value. You must explicitly set the string value for every single member.

Question

Do they support reverse mapping?

Click to reveal answer
Answer

No. Only numeric enums support reverse mapping (`Enum[1]`). String enums only go one way.