8

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 defining 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 appreciate it ;)

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

Comments

3

A more complete example might look something like this:

const formSchema = z.object({ title: z.string(), }) type FormData = z.infer<typeof formSchema> const formOptions: UseFormProps<FormData> = { resolver: ..., defaultValues: ..., } const { handleSubmit } = useForm<FormData>(formOptions) 

Though it's a bit more verbose, the nice thing about this is you'll have typing on your defaultValues as well as the incoming data values in your form submit handler. I hope that helps!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.