In TypeScript, you can convert a string to an enum value by using the enum
and valueOf()
method. Enumerations, or enums, provide a way to define a set of named constants representing discrete values.
#1. Define an Enum
First, you need to define an enum that represents the possible string values.
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
In this example, we define an enum called Color
with three constant values: "RED"
, "GREEN"
, and "BLUE"
.
#2. Convert a String to Enum
To convert a string to an enum value, you can use the valueOf()
method.
function convertToColorEnum(str: string): Color | undefined {
const colorValue = Color[str as keyof typeof Color];
return colorValue;
}
const myColor = convertToColorEnum("GREEN");
if (myColor !== undefined) {
console.log(myColor); // Output: Color.Green
} else {
console.log("Invalid color string.");
}
In this example, we create a function convertToColorEnum()
that takes a string parameter str
. We use str
as a key to access the enum value using the Color
enum as the type. The valueOf()
method converts the string to the corresponding enum value.
#3. Handling Invalid Strings
It is essential to handle scenarios where the input string does not match any enum value.
function convertToColorEnum(str: string): Color | undefined {
const colorValue = Color[str as keyof typeof Color];
return colorValue;
}
const myColor = convertToColorEnum("YELLOW");
if (myColor !== undefined) {
console.log(myColor); // Output: Color.Yellow
} else {
console.log("Invalid color string."); // Output: Invalid color string.
}
In this example, the string "YELLOW"
does not match any enum value, so the function returns undefined
, and the appropriate error message is displayed.
2 Comments
Nice
This doesn't work for me. The code doesn't even use `valueOf()` from what I can see.