String Enums
In this page:
Basic String Enum
Every member of a string enum must have an explicit string value — unlike numeric enums, TypeScript won't auto-assign one, so you always know exactly what string each member represents.
Example: Basic String Enum
enum Status {
Pending = "PENDING",
Done = "DONE",
Failed = "FAILED",
}
console.log(Status.Done);
String Enums in Functions
String enum values work as function parameters the same way numeric ones do, restricting callers to one of the named string choices instead of accepting any arbitrary string.
Example: String Enums in Functions
enum Status { Pending = "PENDING", Done = "DONE" }
function label(status: Status) {
return `Status: ${status}`;
}
console.log(label(Status.Pending));
String Enums and JSON
String enums are especially convenient for values that pass through JSON, since their runtime value is already a plain, readable string — no translation layer needed between the enum and its serialized form.
Example: String Enums and JSON
enum Status { Pending = "PENDING", Done = "DONE" }
const task = { id: 1, status: Status.Done };
console.log(JSON.stringify(task));
String Enum Comparisons
String enum members can be compared directly with each other or used cleanly inside switch statements, and because the values are human-readable, debugging output is far easier to read than with numeric enums.
Example: String Enum Comparisons
enum Status { Pending = "PENDING", Done = "DONE" }
function describe(status: Status) {
switch (status) {
case Status.Pending: return "Still working";
case Status.Done: return "Complete";
}
}
console.log(describe(Status.Done));
When to Use String Enums
Reach for string enums when the values will be stored, logged, or transmitted somewhere and benefit from staying human-readable — a numeric enum wouldn't make sense in a log file or a REST API payload.
Example: When to Use String Enums
enum LogLevel {
Info = "INFO",
Warn = "WARN",
Error = "ERROR",
}
console.log(`[${LogLevel.Warn}] Disk space low`);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: