0

I have an enum in typescript which has 20+ fields. I have UI application where user can put information in some freetext (for example let's say the color the person likes). My requirement is to take this color information and call the midtier service. The midtier service has Color defined as Enum which is kept in sync with UI enum definition. I need to convert the user input text to enum (in front end side) as there are compilation issues being thrown during build. I am not finding a way to perform the conversion (for example from the user input string to a specific enum element). Any pointers will be helpful.

Here is the sample code

       export enum Color {
          green='green',
          orange='orange',
          yellow = 'yellow'
...... 
and so on
       }

User gives the input as green (which is a string). When I am calling the service on midtier, it expects an enum.

Regards

4
  • 3
    yourEnum[ thatString ] ? Hard to tell without a minimal reproducible example Commented Apr 16, 2021 at 22:14
  • just provided the code sample.. please let me know if you need any other details Commented Apr 16, 2021 at 22:20
  • 1
    So your service expects one of ~20 defined colors, but your user can input any text as a value. Ain't that a conflict? What prevents the user from entering something that ain't a value in your enum? Commented Apr 16, 2021 at 22:52
  • Actually we have identified this design issue but as of now our UX designer is working on it. However in order to support existing application, I am working on some enhancement Commented Apr 19, 2021 at 13:20

1 Answer 1

1

TypeScript supports reverse enum mapping. So Color[1] === 'Green', and Color['green'] === 1.

That being said, your UI is likely running TS exported to JS, and this enum does not exist in value-space. If that assumption is correct, you are better off exporting the enum to an object to be mapped in a more vannilla-js way

Sign up to request clarification or add additional context in comments.

1 Comment

thanks.. let me check this. Actually I am more of a server side developer and not fully familiar with these concepts

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.