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

152
Visualizações
Typescript typing for function that takes enums with the same keys

I want to write a helper function for taking two enums that have the same set of keys and returning an array of objects that have the values for the two enums for each of the keys. For example:

enum OptionLabel {
    OPTION_1 = 'label 1',
    OPTION_2 = 'label 2'
}

enum OptionValue {
    OPTION_1 = 'value 1',
    OPTION_2 = 'value 2'
}

const OPTIONS = getOptions(OptionLabel, OptionValue);
// OPTIONS is [{ label: 'label 1', value: 'value 1' }, { label: 'label 2', value: 'value 2' }]

Here is what I have so far:

const getOptions = <LabelEnumType, ValueEnumType>(
    LabelEnum: LabelEnumType,
    ValueEnum: ValueEnumType
): { label: LabelEnumType; value: ValueEnumType }[] =>
    (Object.keys(LabelEnum) as (keyof typeof LabelEnum)[]).map((key) => ({
        label: LabelEnum[key] as unknown as LabelEnumType,
        value: ValueEnum[
            key as unknown as keyof ValueEnumType
        ] as unknown as ValueEnumType,
    }));

As you can see, there is a bunch of undesirable casting going on -- what is the ideal typing here?

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

0

You need to put extra constraint for second generic argument ValueEnumType. Because both enums should have same keys

enum OptionLabel {
    OPTION_1 = 'label 1',
    OPTION_2 = 'label 2'
}

enum OptionValue {
    OPTION_1 = 'value 1',
    OPTION_2 = 'value 2'
}

const getOptions = <
    LabelEnum,
    ValueEnum extends Record<keyof LabelEnum, string>
>(
    LabelEnum: LabelEnum,
    ValueEnum: ValueEnum
) =>
    (Object.keys(LabelEnum) as (keyof typeof LabelEnum)[])
        .map((key) => ({
            label: LabelEnum[key],
            value: ValueEnum[key],
        }));

const OPTIONS = getOptions(OptionLabel, OptionValue);

Playground

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