documentation icon indicating copy to clipboard operation
documentation copied to clipboard

issue: handleSubmit doesn't respect Zod schema transformations in TypeScript

Open gerkim62 opened this issue 1 year ago • 4 comments

Version Number

7.52.0

Codesandbox/Expo snack

https://codesandbox.io/p/devbox/runtime-star-dkcpzz

Steps to reproduce

When using react-hook-form with a Zod schema that includes transformations, the handleSubmit function is passing data to the onSubmit function typed as z.input<typeof Schema> instead of the expected z.output<typeof Schema>. This causes TypeScript errors when trying to access the transformed properties in the submit handler.

To reproduce:

Define a Zod schema with a transformation:

typescriptCopyimport { z } from "zod";

const EmailOrPhoneSchema = z.object({ emailOrPhone: z.string().trim().refine(/* ... /) }) .transform(({ emailOrPhone }) => ({ isEmail: / ... /, isPhone: / ... /, value: / ... */ }));

Use the schema with react-hook-form:

typescriptCopyconst { handleSubmit } = useForm<z.input<typeof EmailOrPhoneSchema>>({ resolver: zodResolver(EmailOrPhoneSchema), });

function onSubmit(data: z.output<typeof EmailOrPhoneSchema>) { console.log(data); // TypeScript error: Property 'isEmail' does not exist on type '{ emailOrPhone: string; }' }

// ...

{/* ... */}

Expected behaviour

The onSubmit function should receive data typed as z.output<typeof EmailOrPhoneSchema>, reflecting the transformation defined in the Zod schema.

What browsers are you seeing the problem on?

No response

Relevant log output

No response

Code of Conduct

  • [X] I agree to follow this project's Code of Conduct

gerkim62 avatar Jun 25 '24 20:06 gerkim62