Búsqueda de sitios web

¿Cómo convertir un string-enum a enum en Reactjs con TypeScript?


Tengo un enum así en un archivo .ts:

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

En otro archivo .tsx, tengo una cadena "12noon" en una variable llamada selectedOption y quiero convertirla en este enum. ¿Cómo puedo hacer eso?

Probé esto basado en las otras respuestas en StackOverflow, pero ninguno funcionó:

var timeInDay: TimeOfDay = TimeOfDay[selectedOption];

Lo anterior está dando el error TS7053.

var timeInDay: TimeOfDay = <TimeOfDay>selectedOption;

Lo anterior está dando errores TS17008 y TS2604.

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

Lo anterior está dando errores TS2339 y TS17008.

He revisado muchas respuestas en este sitio, pero no encontré una solución.

Respuesta #1

Aquí hay algunas formas de usar un string donde se espera un tipo de enumeración de cadenas:

Campo de Juegos TS

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