Generic function to convert string to typescript enum

Issue

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.

Solution

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');

Answered By – Tom Cumming

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.