Thomas Laforge
Thomas Laforge

Reputation: 173

Typescript: string to enum

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

Upvotes: 1

Views: 157

Answers (1)

klugjo
klugjo

Reputation: 20885

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

Upvotes: 1

Related Questions