String Enums

Enums whose members hold readable string values.

Syntaxenum 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

Try it yourself
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.

Example Β· ts
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.

Example Β· ts
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 string

Iterating 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.

Example Β· ts
enum Color { Red = 'red', Green = 'green', Blue = 'blue' }

const allColors = Object.values(Color);
// ['red', 'green', 'blue']

allColors.forEach((c) => console.log(c));

Discussion

  • Be the first to comment on this lesson.
String Enums β€” TypeScript | SoundsCode