Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
Best way to cast an object to a TypeScript Enum Value

Is there an easy/best practice way to cast an any value to a TypeScript Enum and throw an exception if there is no value.

As an example

You have an express request object and are using the query.option value. Your application knows it only has two valid states a|b. However, the reality of the internet and request object is that it can be many things (undefined, a, b, foo).

enum OPTIONS_ENUM {
  a = 'a',
  b = 'b'
}

function handleRequest(req: Request): OPTIONS_ENUM {
  // This will error because query.option is an any
  return OPTIONS_ENUM[req.query?.option]
}

What I have been doing seems a little verbose. I have a "cast" function next to each enum that will throw if the ENUM does not have a value.

function castToOptionsEnum(option: any): OPTIONS_ENUM {
  if (!Object.values(OPTIONS_ENUM)?.includes(option)) {
    throw new Error(`Invalid Value for option, must be one of ${Object.values(OPTIONS_ENUM)}`)
  }
 
  // @ts-ignore
  return OPTIONS_ENUM[option]
}

function handleRequest(req: Request) {
  // This will error because the option query is unknowable 
  return castToOptionsEnum(req.query?.option)
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you can "simply" cast option to OPTIONS_ENUM when accessing OPTIONS_ENUM in castToOptionsEnum:

function castToOptionsEnum(option: any): OPTIONS_ENUM {
    if (!Object.values(OPTIONS_ENUM)?.includes(option)) {
        throw new Error(`Invalid Value for option, must be one of ${Object.values(OPTIONS_ENUM)}`);
    }

    return OPTIONS_ENUM[option as OPTIONS_ENUM];
}

This will remove any compile errors (I would suggest to remove // @ts-ignore aswell, since it "hides" compile errors - but that's up to you ^^).

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda