How do we create an enum with string values?
How do we create an enum with string values?
To create an enum with string values in TypeScript, you can follow several approaches, each suitable for different scenarios depending on your specific requirements. Here are the methods:
The most straightforward way to create an enum with string values is by directly assigning string literals to the enum members. This approach is simple and provides a clear structure for defining a set of named values, each associated with a specific string.
enum Color {
Red = "FF0000",
Green = "00FF00",
Blue = "0000FF",
}
In this example, an enum named Color
is created with string values representing colors in hexadecimal format. You can then use this enum like so:
const myColor: Color = Color.Red;
console.log(myColor); // Output: "FF0000"
This method is beneficial for creating a finite set of values that are known at compile time[8].
Union types allow for more flexibility by combining multiple types with the |
operator. They enable you to specify a variable to be one of several predefined string values without the rigid structure of an enum.
type Color = "FF0000" | "00FF00" | "0000FF";
This approach is more open-ended and is useful when you want to allow any string value within a specified set without necessarily needing the additional structure that enums provide[8].
Object mapping involves creating an object with string values and using the keyof
operator along with typeof
to define a type representing its keys. This method is useful when you want to map strings to more complex values or when you need to ensure the values are u...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào