Is that possible to infer form value from SubmitHandler instead of defining it ourselves? #13031
Replies: 1 comment
|
TypeScript cannot build a form type in reverse from separate The usual approach is to define one source of truth and infer from that source, rather than repeating the shape manually. For example, with a schema: const schema = z.object({
email: z.string().email(),
age: z.number().int(),
})
type FormValues = z.input<typeof schema>
const { register, handleSubmit } = useForm<FormValues>({
resolver: zodResolver(schema),
})
const onSubmit: SubmitHandler<FormValues> = (data) => {
// data is { email: string; age: number }
}For simple forms, const defaultValues = { email: '', age: 0 }
type FormValues = typeof defaultValues
const form = useForm<FormValues>({ defaultValues })You also do not have to annotate a separate handler at all. Once <form onSubmit={handleSubmit((data) => {
// data is FormValues
})}>Redux can expose TypeScript reference: https://react-hook-form.com/ts |
Uh oh!
There was an error while loading. Please reload this page.
export type SubmitHandler<T> = (data: T, event?: React.BaseSyntheticEvent) => unknown | Promise<unknown>Looks like every time we want to submit we'll need to provide our own FormValue instead of using those properties we registered using
registermethod.Would react-hook-form be intelligent enough to provide an inferred type for us to use just like the
RootStatethat Redux provides?All reactions