Search code examples
reactjstypescriptenumstypescript-genericsreact-typescript

How to convert string-enum to enum in Reactjs typescript?


I have an enum like this in a .ts file:

export enum TimeOfDay{
    MORNING = "AM",
    NOON = "12noon",
    EVENING = "PM",
    MIDNIGHT = "12midnight"
}

In another .tsx file, I have a string "12noon" in a variable named selectedOption and I want to convert it into this enum. How can I do that?

I tried these based on the other answers in StackOverflow, but none of the worked:

var timeInDay: TimeOfDay = TimeOfDay[selectedOption];

The above is giving TS7053 error.

var timeInDay: TimeOfDay = <TimeOfDay>selectedOption;

The above is giving TS17008 and TS2604 errors.

var timeInDay: TimeOfDay = (<any>TimeOfDay)[selectedOption];

The above is giving TS2339 and TS17008 errors.

I've gone through many answers on this site but didn't find a solution.


Solution

  • Here are some ways to use a string where a string enum type is expected:

    TS Playground

    enum TimeOfDay{
      MORNING = "AM",
      NOON = "12noon",
      EVENING = "PM",
      MIDNIGHT = "12midnight"
    }
    
    function doSomethingWithTimeOfDay (time: TimeOfDay): void {
      console.log(time);
    }
    
    const selectedOption = '12noon';
    
    // As you observed, this doesn't work:
    doSomethingWithTimeOfDay(selectedOption);
    //                       ~~~~~~~~~~~~~~
    // Argument of type '"12noon"' is not assignable to parameter of type 'TimeOfDay'.
    
    // Use a predicate to check at runtime:
    function isTimeOfDay (value: string): value is TimeOfDay {
      return Object.values(TimeOfDay).includes(value as TimeOfDay);
    }
    
    if (isTimeOfDay(selectedOption)) {
      doSomethingWithTimeOfDay(selectedOption); // ok
    }
    
    // Or, if you're certain that the string is a valid string enum value,
    // then you can use an assertion:
    doSomethingWithTimeOfDay(selectedOption as TimeOfDay); // ok