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.
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";
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.