React-hook-form中handleSubmit参数的类型

Max*_*een 6 typescript reactjs react-hook-form

我在函数中遇到 TypeScript 错误handleSubmit

  1. 我正在handleSubmit通过以下方式检索功能useForm
const {handleSubmit, control, watch, reset} = useForm()
Run Code Online (Sandbox Code Playgroud)
  1. 我正在定义提交功能:
const submit = (data: { file: File, crop: Area }) => {
    onSubmit(data.file, data.crop)  // onSubmit is passed from parent component
}
Run Code Online (Sandbox Code Playgroud)
  1. 我传入handleSubmit组件的onSubmitpropForm
<Form onSubmit={handleSubmit(submit)}>
    // registering form fields here
</Form>
Run Code Online (Sandbox Code Playgroud)
  1. 出现以下 TypeScript 错误:
 Argument of type '(data: {    file: File;    crop: Area;}) => void' is not assignable to parameter of type 'SubmitHandler<FieldValues>'.
[1]   Types of parameters 'data' and 'data' are incompatible.
[1]     Type '{ [x: string]: any; }' is missing the following properties from type '{ file: File; crop: Area; }': file, crop  TS2345
Run Code Online (Sandbox Code Playgroud)

如果我handleSubmit像这样通过,一切都会正常。

 Argument of type '(data: {    file: File;    crop: Area;}) => void' is not assignable to parameter of type 'SubmitHandler<FieldValues>'.
[1]   Types of parameters 'data' and 'data' are incompatible.
[1]     Type '{ [x: string]: any; }' is missing the following properties from type '{ file: File; crop: Area; }': file, crop  TS2345
Run Code Online (Sandbox Code Playgroud)

但我试图不在any我的项目中使用。因此,如果有人可以解释我应该如何为handleSubmit函数输入参数,我将不胜感激。;)

Rob*_*ert 13

submit()您只需将与添加到函数的,相同的类型添加datauseForm挂钩即可。

因此,在您的示例中,您可以创建一个新类型:

type Data = { 
  file: File; 
  crop: Area;
}
Run Code Online (Sandbox Code Playgroud)

并将其传递给两个submit()函数:

const submit = (data: Data) => {
// ...
Run Code Online (Sandbox Code Playgroud)

useForm()钩子:

const {handleSubmit, control, watch, reset} = useForm<Data>()
Run Code Online (Sandbox Code Playgroud)

那么它应该可以工作:)

据我了解,提供给 的submit()数据的类型仅提供有关向submit()函数键入的信息。

但由于该函数也作为参数向下传递,因此handleSubmit(),handleSubmit()需要了解传递submit()的数据的类型。我们可以让它知道这种类型,只需将其提供给钩子即可useForm