I found this great answer about how to convert a string to a typescript enum. Based on that I have written this function
enum Color { Red='red', Green='green' }
function mapColorString(strColor: string): Color {
const colorKey = strColor as keyof typeof Color
return Color[colorKey]
}
But now when I try to make it generic,
function getEnumFromString<T>(str: string): T {
const enumKey = str as keyof T
return T[enumKey]
}
I get the error in the return statement: 'T' only refers to a type, but is being used as a value here.
I want to make this generic because I have a number of enums that I need to generate based on their string values, and I would like to not have a separate method for every one.
To convert a string to an enum: Use keyof typeof to cast the string to the type of the enum. Use bracket notation to access the corresponding value of the string in the enum.
We can convert an enum to string by calling the ToString() method of an Enum. The following code example shows how to convert an enum to a string in C#.
Alternatives to enums: string unions and object literals.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
I can get this to work when i pass the enum definition:
enum Color { Red='red', Green='green' }
function getEnumFromString<T>(type: T, str: string): T[keyof T] {
const casted = str as keyof T;
return type[casted];
}
const bar = getEnumFromString(Color, 'Red');
T
is just going to be the type of the enum. Types are erased and don't exist at runtime. You need to pass in the object representing the enum:
enum Color { Red='red', Green='green' }
function getEnumFromString<T, K extends string>(enumObj: { [P in K]: T },str: string): T {
const enumKey = str as K
return enumObj[enumKey]
}
getEnumFromString(Color, 'Red');
K
will represent the keys of the enum, T
will be the type for the enum value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With