0
0
Typescriptprogramming~5 mins

String enums in Typescript

Choose your learning style9 modes available
Introduction

String enums let you group related string values under one name. This helps keep your code clear and easy to understand.

When you want to represent a fixed set of string options, like directions ("North", "South", "East", "West").
When you need to avoid typos by using named constants instead of raw strings.
When you want to make your code easier to read and maintain by giving meaningful names to string values.
Syntax
Typescript
enum EnumName {
  Member1 = "stringValue1",
  Member2 = "stringValue2",
  Member3 = "stringValue3"
}

Each member must be assigned a string value explicitly.

String enums are useful for readable and safe code instead of using plain strings.

Examples
This enum groups four directions as string values.
Typescript
enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}
This enum represents possible status values as strings.
Typescript
enum Status {
  Success = "SUCCESS",
  Failure = "FAILURE",
  Pending = "PENDING"
}
Sample Program

This program defines a string enum for colors and prints one color using the enum.

Typescript
enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

function printColor(color: Color) {
  console.log(`The color is: ${color}`);
}

printColor(Color.Green);
OutputSuccess
Important Notes

You cannot mix string enums with numeric enums in the same enum.

Using string enums helps prevent mistakes from typing strings directly.

Summary

String enums group related string values under named constants.

They make code easier to read and safer by avoiding raw strings.

Each enum member must have an explicit string value.