CodexBloom - Programming Q&A Platform

Next.js 13 Form Handling with React Hook Form and Zod - Type Inference Issues

👀 Views: 36 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
next.js react-hook-form zod typescript

After trying multiple solutions online, I still can't figure this out. I'm currently working on a form in a Next.js 13 application using React Hook Form and Zod for validation. I set up my form validation schema with Zod and connected it with React Hook Form, but I'm running into type inference issues that lead to unexpected behavior during form submission. Specifically, the types of the form values don't seem to match what I defined in my Zod schema. Here's a snippet of my code: ```javascript import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; const schema = z.object({ username: z.string().min(1, 'Username is required'), age: z.number().min(18, 'You must be at least 18').max(99, 'Age must be less than 100'), }); export default function MyForm() { const { register, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(schema), }); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register('username')} /> {errors.username && <p>{errors.username.message}</p>} <input type='number' {...register('age')} /> {errors.age && <p>{errors.age.message}</p>} <button type='submit'>Submit</button> </form> ); } ``` When I run this, I get a TypeScript behavior saying that `data` might not conform to the inferred type of the schema. The behavior message reads: `Argument of type 'unknown' is not assignable to parameter of type 'z.infer<typeof schema>'`. I've ensured that the Zod schema is defined correctly, but it's as if TypeScript need to infer the correct types from the schema within the `onSubmit` function. I've already tried adding type annotations to the `data` parameter like this: ```javascript const onSubmit = (data: z.infer<typeof schema>) => { console.log(data); }; ``` Yet, this doesn't resolve the scenario. I'm also using TypeScript version 4.5.4, React Hook Form version 7.22.1, and Zod version 3.10.1. Is there a known workaround for this type inference scenario? What am I missing in the setup that could lead to this mismatch? My development environment is Linux. I'd really appreciate any guidance on this.