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

146
Visualizações
Convert enum to array of objects

I have an enum defined as following:

export enum SwitchEnum{
  On = 'ON',
  Off = 'OFF',
}

I want to create a an array of objects from this enum so I tried as following:

export interface SelectProps {
  id: number;
  value: string | number | undefined;
  label: string | undefined;
}

const listItems: SelectProps [] = Object.keys(SwitchEnum).map((key, index) => ({
  id: index,
  value: SwitchEnum[key],
  label: key
}));

But Typescript is complaining with this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof SwitchEnum'.
  No index signature with a parameter of type 'string' was found on type 'typeof SwitchEnum'

How can I solve this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In TypeScript, enums are used as types at compile-time to achieve type-safety for the constants but they are treated as objects at runtime. This is because, they are converted to plain objects once the TypeScript code is compiled to JavaScript. So, the explanation of the objects above is applicable here too. So to fix the typeScript error you should change your code into this:

const listItems: SelectProps [] = Object.keys(SwitchEnum).map((key,index) => ({
 id: index,
 value: SwitchEnum[key as keyof typeof SwitchEnum],
 label: key
}));
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