Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!