1

How do I transform a string to an enum type in Typescript. I want to return a list of all elements of my enum by passing the name of an enum with a string

For example:

enum Toto {A, B, C, D}
enum Autre {F, G, H}
...
...

extract(enumName: string) {
   // todo
   return Object.keys(definition)
      .map(key => ({ value: definition[key], title: key }));
}

definition will be one of the Enum.

For instance, if I run extract('toto'), the function must find Toto and inject it into Object.key and return [{A,A},{B,B}, {C,C}, {D,D}]

The issue is I cannot find my enum from my string.

Thank you for your help

1
  • What is the definition in your code, first of all? Commented Aug 26, 2019 at 3:31

1 Answer 1

1

I don't think there is a way to get an enum name at runtime.

You are better off maintaining a simple mapping string <-> enum. That will make your life easier anyways.

enum Toto {A, B, C, D}
enum Autre {F, G, H}

const enumMapping: {[key: string]: any} = {
    Toto: Toto,
    Autre: Autre
};

const extract = (enumName: string) => {
   const definition = enumMapping[enumName];

   if (!definition) {
       return null;
   }

   return Object.keys(definition)
      .map(key => ({ value: definition[key], title: key }));
}

console.log(extract('Toto'));
console.log(extract('Autre'));
console.log(extract('Will return null'));
Sign up to request clarification or add additional context in comments.

1 Comment

yes, I wrote a mapping also, but I was aiming for a more dynamic solution. Thank you for your answer and your time

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.