简体   繁体   中英

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>>'

在此处输入图像描述

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

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']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM