react-select wrapped with react-hook-form Controller TS compiler error?

Viewed 46

I would like to pass generic to my custom Select component. I am using "react-hook-form": "^7.33.1", and "react-select": "^5.4.0".

I named it ReactSelect which gets control type as a generic.

export interface EditAuthorData {
  name: string;
  born: number;
}
...
  <ReactSelect<EditAuthorData>
        control={control}
        name="name"
        placeholder="Select author..."
        options={options}
      />

Select component is wrapped with react-hook-form's Controller component. It looks like this

type ReactSelectProps<T> = {
  name: string;
  control: Control<T>;
  placeholder: string;
  options: Option[];
};

export function ReactSelect<T extends object>({
  name,
  control,
  placeholder,
  options,
}: ReactSelectProps<T>) {
  return (
    <Controller
      control={control}
      name={name}
      render={({ field: { onChange, value } }) => {
        return (
          <Select
            options={options}
            onChange={(e) => {
              if (e) {
                onChange(e.value);
              }
            }}
            value={options.filter((option) => value?.includes(option.value))}
            placeholder={placeholder}
          />
        );
      }}
    />
  );
}

But for some reason, I am getting this ts error and I can't understand what am I doing wrong.

Type 'string' is not assignable to type 'Path<T>'.ts(2322)
controller.d.ts(24, 5): The expected type comes from property 'name' which is declared here on type 'IntrinsicAttributes & { render: ({ field, fieldState, formState, }: { field: ControllerRenderProps<T, Path<T>>; fieldState: ControllerFieldState; formState: UseFormStateReturn<...>; }) => ReactElement<...>; } & UseControllerProps<...>'

Here is the link to the whole code in codesandbox: https://codesandbox.io/s/react-hook-form-error-fvuku5?file=/src/ui/select/ReactSelect.tsx

1 Answers

name: string is wrong, see Controller code, its props are generic too, so you need to properly type it

Related