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?
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);