How to useEnums in Typescript
Enums provide a structured way to define a set of named values, associating each with a specific string.
Example: In this example, we define an enum Color
with string values representing red, green, and blue. We then assign the Red
value to myColor
and log it, resulting in the output “FF0000.”
// Creating an enum named Color with string values
enum Color {
Red = "FF0000",
Green = "00FF00",
Blue = "0000FF",
}
// Using the enum
const myColor: Color = Color.Red;
console.log(myColor);
Output:
FF0000
How to Create an Enum With String Values in TypeScript ?
To create an enum with string values in TypesScript, we have different approaches. In this article, we are going to learn how to create an enum with string values in TypesScript.
Below are the approaches used to create an enum with string values in TypesScript:
Table of Content
- Approach 1: Using Enums
- Approach 2: Using Union Types
- Approach 3: Using Object Mapping
- Approach 4: Using String Literal Types with Const Assertion
Contact Us