Enums
Enums (short for enumerations) in TypeScript are a feature that allows you to define a set of named constants. They provide a human-readable way to represent a set of constant values, which might otherwise be represented as numbers or strings.
Example 1: Game Controls
Letβs say you have a game where you have to perform an action based on whether the user has pressed the up, down, left, or right arrow key.
This makes the code cleaner and easier to understand. At runtime, the values stored are still numbers (0, 1, 2, 3).
2. Runtime Values of Enums
Let's log the runtime value of Direction.Up
:
By default, enums get values starting from 0 and incrementing by 1 for each subsequent member.
3. Customizing Enum Values
You can customize the values of enums:
4. Using String Values
Enums can also be represented as strings:
5. Common Use Case in Express
Enums are commonly used in frameworks like Express to represent status codes:
Enums provide a convenient way to define a set of related constants and improve code readability and maintainability. They are widely used in various scenarios, including game development, web frameworks, and API development.
Last updated
Was this helpful?