Translate

Friday, 16 February 2024

What is Enum type in Typescript ? 061

 What is Enum type in Typescript ?


An enum in TypeScript is a special kind of data type that allows you to define a set of named constants. These constants are restricted to a specific set of values, enhancing code readability and maintainability. Here's a breakdown of key aspects:

Purpose:

  • Enums group related constants under a single type, making your code more self-documenting and preventing accidental use of invalid values.

  • They ensure type safety, meaning the compiler will catch attempts to assign non-enum values to enum variables.

Types:

  • Enums can be either string enums or numeric enums.

  • String enums: Each member has a string value (e.g., Color.Red = "red").

  • Numeric enums: Members have numerical values, usually starting from 0 and incrementing by default (e.g., DaysOfWeek.Monday = 0). You can explicitly assign values as well.

Syntax:


TypeScript

// String enum
enum Color { Red = "red", Green = "green", Blue = "blue" }

// Numeric enum (explicit values)
enum DaysOfWeek { Monday = 1, Tuesday, Wednesday, Thursday = 4, Friday }

Accessing Values:

  • Use the enum name followed by dot notation to access member values:


TypeScript

const myColor: Color = Color.Green;
console.log("Day number:", DaysOfWeek.Wednesday);

Reverse Mapping:

  • You can retrieve the enum member name from its value using reverse mapping:


TypeScript

const name = Color[myColor]; // name will be "Green"

Benefits:

  • Type safety: Prevents invalid values from being assigned to enum variables.

  • Readability: Self-documenting code by explicitly naming constants.

  • Maintainability: Makes code easier to understand and modify.

  • Completions and linting: IDEs and linters can provide better support for enums.

Use Cases:

  • Representing error codes, status codes, permission levels, weekdays, months, etc.

  • Creating sets of options for configuration settings or user choices.

In summary, enums are a valuable tool in TypeScript for defining named constants, improving code clarity, and ensuring type safety.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.