Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the correct typescript type for setValue in react-hook-form?

I want to pass the function setValue() down to a child component. Then I get the following error message:

Type 'UseFormSetValue<Inputs>' is not assignable to type 'UseFormSetValue<Record<string, any>>'

enter image description here

How can I pass down the function correctly?

Sandbox example

function App() {
  const {
    register,
    setValue,
  } = useForm<Inputs>({
  });

  return (
    <form>
      <Field2 setValue={setValue} register={register} />
      <input type="submit" />
    </form>
  );
}
like image 949
vuvu Avatar asked Oct 22 '25 23:10

vuvu


1 Answers

The default UseFormReturn["setValue"] type resolves to UseFormSetValue<Record<string, any>>. You can explicitly configure the setValue type to use the correct generic params like this:

setValue: UseFormSetValue<Inputs>;

Instead of:

setValue: UseFormReturn["setValue"];

Note: All public types can be imported from react-hook-form module

import {
  UseFormReturn,
  UseFormSetValue
} from "react-hook-form";

Live Demo

I also fixed your related type error in register props in the live demo (UseFormRegister<Inputs> instead of UseFormReturn['register']

Edit 67285413/how-to-set-correct-typescript-type-for-setvalue-in-react-hook-form

like image 158
NearHuscarl Avatar answered Oct 24 '25 15:10

NearHuscarl