Type of handleSubmit parameter in react-hook-form

Viewed 1137

I have a TypeScript error in handleSubmit function.

  1. I'm retrieving handleSubmit function via useForm:
const {handleSubmit, control, watch, reset} = useForm()
  1. I'm difining submit function:
const submit = (data: { file: File, crop: Area }) => {
    onSubmit(data.file, data.crop)  // onSubmit is passed from parent component
}
  1. I pass handleSubmit in onSubmit prop of Form component
<Form onSubmit={handleSubmit(submit)}>
    // registering form fields here
</Form>
  1. Got the following TypeScript error:
 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

If i pass handleSubmit like this everything works fine.

<Form onSubmit={handleSubmit(submit as any)}></Form>

But i'm trying not to use any in my project. So if anyone could explain how should i type parameter for handleSubmit function i will aprecciate it. ;)

1 Answers

You can just add the same type as you add to the submit() function's data, to the useForm hook.

So in your example, you can just make a new type:

type Data = { 
  file: File; 
  crop: Area;
}

and pass it to both, submit() function:

const submit = (data: Data) => {
// ...

and useForm() hook:

const {handleSubmit, control, watch, reset} = useForm<Data>()

Then it should work :)

As I understand it, type provided to the submit()'s data gives information about typing only to the submit() function.

But because this function is also passed down as an argument, to the handleSubmit(), handleSubmit() needs to know about the type of passed submit()'s data. And we can let it know about this type, simply by providing it to the useForm hook.

Related