I am trying to create a generic select box using react-hook-form
and react-select
:
import { Control, Controller, FieldPath, FieldPathValue, FieldValues } from "react-hook-form";
import ReactSelect from "react-select";
interface SelectProps<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> {
name: TName;
defaultValue: FieldPathValue<TFieldValues, TName>;
items: FieldPathValue<TFieldValues, TName>[];
getOptionValue: (item: FieldPathValue<TFieldValues, TName>) => string;
getOptionLabel: (item: FieldPathValue<TFieldValues, TName>) => string;
control: Control<TFieldValues>;
}
function Select<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({ name, defaultValue, items, getOptionValue, getOptionLabel, control }: SelectProps<TFieldValues, TName>) {
return (
<Controller
name={name}
control={control}
defaultValue={defaultValue}
render={({ field }) => (
<ReactSelect {...field} options={items} getOptionValue={getOptionValue} getOptionLabel={getOptionLabel} />
)}
/>
);
}
export default Select;
Then I use it followings:
<Select2<MyType>
name={"path.of.the.subProperty"}
control={controlTakenFromUseForm}
items={myItems}
defaultValue={myDefaultValue}
getOptionValue={(item: any) => item.valueProperty}
getOptionLabel={(item: any) => item.labelProperty}
/>
The problem are the types of the two any
items, which are the union of all MyType
properties and its subtypes. How can I make it generic in order that the item of the two functions is typed? Actually, the SelectComponent get it fro the items
property.