如何在 react-hook-form 中为 setValue 设置正确的打字稿类型?

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

我想将函数 setValue() 传递给子组件。然后我收到以下错误消息:

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

如何正确传递函数?

Sandbox example

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

  return (
    <form>
      <Field2 setValue={setValue} register={register} />
      <input type="submit" />
    </form>
  );
}

默认 UseFormReturn["setValue"] 类型解析为 UseFormSetValue<Record<string, any>>。您可以显式配置 setValue 类型以使用正确的通用参数,如下所示:

setValue: UseFormSetValue<Inputs>;

而不是:

setValue: UseFormReturn["setValue"];

注意:所有 public 类型都可以从 react-hook-form 模块导入

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

现场演示

我还修复了您在现场演示中注册道具的相关类型错误(UseFormRegister<Inputs> 而不是 UseFormReturn['register']