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

144
Vistas
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 Respuestas
Responde la pregunta

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 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