String Enums
Enums whose members hold readable string values.
Syntax
enum Status { Active = "ACTIVE" }A string enum assigns a string to each member. These are easier to debug than numeric enums because the values are meaningful when logged.
Every member of a string enum must be given an explicit value.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A logging library uses a string enum for log levels so serialised log entries contain human-readable level names.
- An API client uses a string enum for HTTP methods so network requests are typed and debuggable without numeric lookup.
- A theme system uses a string enum for colour schemes so the active theme name can be directly used in CSS class generation.
More examples
String enum declaration
Uses string enum members so the level name appears directly in the log output without a numeric-to-name lookup.
enum LogLevel {
Debug = 'DEBUG',
Info = 'INFO',
Warn = 'WARN',
Error = 'ERROR',
}
function log(level: LogLevel, message: string): void {
console.log(`[${level}] ${message}`);
}
log(LogLevel.Error, 'Something went wrong');String enum in a union check
Assigns string values that map directly to CSS class names, avoiding a separate name-to-class mapping.
enum Theme { Light = 'light', Dark = 'dark' }
function applyTheme(theme: Theme): void {
document.body.className = theme; // 'light' or 'dark'
}
applyTheme(Theme.Dark);
applyTheme('light' as Theme); // cast required when using raw stringIterating string enum values
Extracts all string values from a string enum using Object.values, which is cleaner than with numeric enums that have reverse mappings.
enum Color { Red = 'red', Green = 'green', Blue = 'blue' }
const allColors = Object.values(Color);
// ['red', 'green', 'blue']
allColors.forEach((c) => console.log(c));
Discussion