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.77k stars 161 forks source link

yupResolver() type mismatch with useForm() when required() on field with null default value #589

Closed ypresto closed 1 year ago

ypresto commented 1 year ago

Describe the bug

Since v3.1.1, yupResolver() causes type mismatch between required() field and null value in defaultValues.

Probably caused by this PR: https://github.com/react-hook-form/resolvers/pull/563

@hookform/resolvers: v3.1.1 react-hook-form: v7.45.1 yup: v1.2.0

To Reproduce

  1. Prepare form with useForm({ defaultValues, resolver: yupResolver(validationSchema) }).
  2. Add a null property (named food in codesandbox) to defaultValues (or just defaultValues: { food: null }).
  3. Mark that property (food) as string().required() in validationSchema.
  4. Type error at useForm(...).

One example of type error:

Type 'Resolver<{ food: {}; }, any>' is not assignable to type 'Resolver<FormValues, any>'.
  Types of parameters 'values' and 'values' are incompatible.
    Type 'FormValues' is not assignable to type '{ food: {}; }'.
      Types of property 'food' are incompatible.
        Type 'FoodGroup | null' is not assignable to type '{}'.
          Type 'null' is not assignable to type '{}'.ts(2322)

Codesandbox link (Required)

https://codesandbox.io/s/react-hook-form-yupresolver-null-type-error-with-tfieldvalues-cd3tcc?file=/src/App.tsx:842-873

(Note: template for yupResolver is too old as it uses v6 of react-hook-form.)

Expected behavior No type error found.

Note that react-select will set the value to null when it is cleared.

ivomasterche commented 1 year ago

Hi, I have the same issue, and opened discussion here (still no replies) https://github.com/orgs/react-hook-form/discussions/10618

Zerebokep commented 1 year ago

I think my problem is also related: https://github.com/orgs/react-hook-form/discussions/10660

jorisre commented 1 year ago

Related to #575

ivomasterche commented 1 year ago

asegarra suggestion fixed the issue https://github.com/react-hook-form/resolvers/issues/575#issuecomment-1693405121 for me too.

Adding NULL as a possible value for the input(select) in the FormInputType and specifying this type resolver: yupResolver<FormInputs>(schema),

was accepted and now there are no type errors.

jorisre commented 1 year ago

@ypresto null is recognized as a value within the context, but the issue arises because your schema doesn't permit values that can be null. This discrepancy is the cause of the error you're encountering. In the most recent update, you have the option to provide your own schema or enable the resolver to deduce types automatically.