Enum in TypeScript

Enums, short for enumerations, are a powerful feature in TypeScript that allow you to define a set of named constants. These constants represent a fixed set of values and can be used to improve code readability, maintainability, and type safety.

Types of Enums

TypeScript supports two types of enums:

  1. Numeric enums: These enums start with a value of 0 by default, and each subsequent member automatically increments by 1. You can also explicitly assign values to specific enum members.
  2. String enums: These enums contain string values instead of numbers. This can be useful when working with values that are more descriptive or human-readable.

Creating Enums

There are two ways to create enums in TypeScript:

Using the enum keyword: This is the most common way to create enums. You can define an enum with a name and its members within curly braces.

enum Direction { Up, Down, Left, Right, } enum StatusCodes { OK = 200, BadRequest = 400, Unauthorized = 401, Forbidden = 403, NotFound = 404, }

Running the TypeScript compiler (tsc) will generate the following JavaScript code:

var Direction; (function (Direction) { Direction[Direction["Up"] = 0] = "Up"; Direction[Direction["Down"] = 1] = "Down"; Direction[Direction["Left"] = 2] = "Left"; Direction[Direction["Right"] = 3] = "Right"; })(Direction (Direction = {})); var StatusCodes; (function (StatusCodes) { StatusCodes[StatusCodes["OK"] = 200] = "OK"; StatusCodes[StatusCodes["BadRequest"] = 400] = "BadRequest"; StatusCodes[StatusCodes["Unauthorized"] = 401] = "Unauthorized"; StatusCodes[StatusCodes["Forbidden"] = 403] = "Forbidden"; StatusCodes[StatusCodes["NotFound"] = 404] = "NotFound"; })(StatusCodes (StatusCodes = {}));

Using const enums

These enums are created using the const keyword and are not accessible at runtime. They are useful for optimization and reducing code size.

const enum Keys { Up = "ArrowUp", Down = "ArrowDown", Left = "ArrowLeft", Right = "ArrowRight", }

Benefits of Using Enums

  1. Readability: Enums make your code more readable and understandable by using descriptive names instead of magic numbers or strings.
  2. Maintainability: Enums help you maintain code consistency and prevent errors by ensuring that only valid values are used.
  3. Type safety: Enums improve type safety by providing a compile-time check for the types of values assigned to variables and function parameters.
  4. Documentation: Enums serve as a form of documentation within your code, clarifying what values are allowed for a specific context.

Accessing Enum Values

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, } console.log(Day.Tuesday); // Output: 2 console.log(Day[2]); // Output: "Tuesday"

Running the TypeScript compiler (tsc) will generate the following JavaScript code:

var Day; (function (Day) { Day[Day["Sunday"] = 0] = "Sunday"; Day[Day["Monday"] = 1] = "Monday"; Day[Day["Tuesday"] = 2] = "Tuesday"; Day[Day["Wednesday"] = 3] = "Wednesday"; Day[Day["Thursday"] = 4] = "Thursday"; Day[Day["Friday"] = 5] = "Friday"; Day[Day["Saturday"] = 6] = "Saturday"; })(Day (Day = {})); console.log(Day.Tuesday); // Output: 2 console.log(Day[2]); // Output: "Tuesday"

You can access enum values by their numeric value or by using reverse mapping with the enum member name.

Function parameters

Enums can be used to restrict the type of data that can be passed as a function parameter.

function setDirection(direction: Direction): void { // Do something based on the direction console.log(`Current direction: ${direction}`); } setDirection(Direction.Up);

Variable declarations

Enums can be used to define the type of a variable and ensure that only valid values are assigned.

let status: StatusCodes; status = StatusCodes.OK; //status = "Success"; // Error: Type '"Success"' is not assignable to type 'StatusCodes'.

Using Enums in Switch Statements

enum TrafficLight { Red, Yellow, Green, } function getTrafficLightMessage(color: TrafficLight): string { switch (color) { case TrafficLight.Red: return "Stop"; case TrafficLight.Yellow: return "Proceed with caution"; case TrafficLight.Green: return "Go"; default: return "Invalid color"; } } console.log(getTrafficLightMessage(TrafficLight.Green)); // Output: "Go"

Running the TypeScript compiler (tsc) will generate the following JavaScript code:

var TrafficLight; (function (TrafficLight) { TrafficLight[TrafficLight["Red"] = 0] = "Red"; TrafficLight[TrafficLight["Yellow"] = 1] = "Yellow"; TrafficLight[TrafficLight["Green"] = 2] = "Green"; })(TrafficLight (TrafficLight = {})); function getTrafficLightMessage(color) { switch (color) { case TrafficLight.Red: return "Stop"; case TrafficLight.Yellow: return "Proceed with caution"; case TrafficLight.Green: return "Go"; default: return "Invalid color"; } } console.log(getTrafficLightMessage(TrafficLight.Green)); // Output: "Go"

Enums are often used in switch statements to improve code readability.

Heterogeneous Enums

enum Result { Success = "SUCCESS", Error = 500, } console.log(Result.Success); // Output: "SUCCESS" console.log(Result.Error); // Output: 500

Enums can have a mix of string and numeric values in a heterogeneous manner.

Enums with Union Types

enum Shape { Circle = "CIRCLE", Square = "SQUARE", Triangle = "TRIANGLE", } type ShapeType = Shape.Circle Shape.Square Shape.Triangle; let myShape: ShapeType = Shape.Circle; console.log(myShape); // Output: "CIRCLE"

Enums can be used in union types for more structured type definitions.

Conclusion

TypeScript enums allow developers to define sets of named constants, improving code readability and maintainability. Enums can have numeric or string values, support custom values, and are useful for creating structured sets of related constants in TypeScript.