react-hook-form / resolvers

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS
https://react-hook-form.com/
MIT License
1.67k stars 151 forks source link

Zodresolver `getFieldState(..).error` type is incorrect #673

Closed voinik closed 2 months ago

voinik commented 2 months ago

Describe the bug This is regarding the Zodresolver. The type of getFieldState(..).error is incorrect when using a schema inside an array schema. It is currently typed as FieldError | undefined, but it should be typed as Merge<FieldError, (FieldError | undefined)[]> | undefined, just like formState.errors.<field> is.

At least, that is how the code behaves. I'm not sure if that new type will still fulfill the Resolver type, though.

To Reproduce Steps to reproduce the behavior:

See the instructions in the codesandbox (copy pasted below):

Instructions:

  1. Notice how there are no errors starting out

  2. Click "Submit"

  3. Notice how form.getFieldState("files").error?.message is filled. That is because the error is on the array level of the schema (z.arr(..).min(1))

  4. Click "Choose files" and add a file

  5. Notice how form.getFieldState("files").error?.message is no longer filled. It's undefined (see console)

  6. But notice now that form.getFieldState("files").error?.[0]?.message IS filled. Same goes for form.formState.errors.files?.[0]?.message

  7. So getFieldState(..).error should share the signature of formState.errors.x, namely Merge<FieldError, (FieldError | undefined)[]> | undefined. However, it is typed only as FieldError | undefined

  8. Check the code and look for the type error and my comment. You can verify the incorrect types there

Codesandbox link (Required) Codesandbox link here

Expected behavior I expect the type of getFieldState(..).error to be Merge<FieldError, (FieldError | undefined)[]> | undefined, instead of FieldError | undefined, which is the same as formState.errors.<field>.

Desktop (please complete the following information):

voinik commented 2 months ago

This is not an issue with @hookform/resolvers, but rather an issue with react-hook-form. My bad! New issue here: https://github.com/react-hook-form/react-hook-form/issues/11814#issue-2260893858