React-hook-form: Typed submission data

Created on 5 Nov 2019  路  3Comments  路  Source: react-hook-form/react-hook-form

Describe the question?

I'm trying to figure out how to get a strongly typed object in onSubmit with the actual key and value types used in my form.

To Reproduce
Steps to reproduce the behavior:

  1. Use the OnSubmit<Record<string, any>> type and notice that Typescript doesn't know whether a field is on the form, or what type the value is.

I tried to write an interface and use OnSubmit<FormValues> but this caused other type errors.

Codesandbox link
https://codesandbox.io/s/fancy-forest-qz722?fontsize=14

That runs fine, but Typescript complains:

Argument of type 'OnSubmit<FormValues>' is not assignable to parameter of type 'OnSubmit<Record<string, any>>'.
  Type 'Record<string, any>' is missing the following properties from type 'FormValues': username, passwordts(2345)

I'm hoping to find a way to easily pass a type to OnSubmit that will allow me to get that type back in the callback as the data parameter.

question

Most helpful comment

why not type in the useForm?

const { register, handleSubmit } = useForm<FormData>();

All 3 comments

why not type in the useForm?

const { register, handleSubmit } = useForm<FormData>();

Exactly what I needed, didn't see that option, thank you!

no worries :) i have documented here as well https://react-hook-form.com/api#TypeScript

Was this page helpful?
0 / 5 - 0 ratings