Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda