Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function to convert string to typescript enum

Tags:

typescript

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.

like image 877
Zach Posten Avatar asked Oct 25 '18 14:10

Zach Posten


People also ask

How do I convert a string to enum in TypeScript?

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.

What is the method to convert an enum type to a string type?

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#.

What can I use instead of enums TypeScript?

Alternatives to enums: string unions and object literals.

Can enum be converted to string?

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.


2 Answers

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');
like image 154
Tom Cumming Avatar answered Sep 30 '22 18:09

Tom Cumming


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

like image 32
Titian Cernicova-Dragomir Avatar answered Sep 30 '22 18:09

Titian Cernicova-Dragomir