I encountered an issue while trying to create a function to format options for dropdown.
This is the code in vanilla JS.
const formatOptions = (options, keyAsLabel, keyAsValue) => {
return options.map(option) => {
return {
label: option[keyAsName],
value: option[keyAsValue],
}
})
}
Currently, I have tried this code
const formatOptions = <T>(
options: T[],
keyAsLabel: T,
keyAsValue: T
) => {
return options.map((option, i) => {
return {
id: i 1,
label: option[keyAsLabel],
value: option[keyAsValue],
}
})
}
But this code is giving error.
I want to make a strict type checking, but I have no idea how to make the second and the third parameter dependent on the first Parameter
CodePudding user response:
Try using keyof
:
const formatOptions = <T>(
options: T[],
keyAsLabel: keyof T,
keyAsValue: keyof T
) => {
return options.map((option, i) => {
return {
id: i 1,
label: option[keyAsLabel],
value: option[keyAsValue],
};
});
};