issue: [yup] Schemas with optional fields cause type errors
Version Number
5.0.1
Codesandbox/Expo snack
https://codesandbox.io/p/sandbox/react-hook-form-resolver-issue-2t3cqg
Steps to reproduce
- Open Codesandbox url
- See line 13 of src/App.tsx
- The following type error occurs.
Type 'Resolver<{ hoge: string | undefined; }, any, { hoge?: string | undefined; }>' is not assignable to type 'Resolver<{ hoge?: string | undefined; }, any, { hoge?: string | undefined; }>'. Types of parameters 'values' and 'values' are incompatible. Type '{ hoge?: string | undefined; }' is not assignable to type '{ hoge: string | undefined; }'.typescript(2322)
Expected behaviour
No type errors
What browsers are you seeing the problem on?
No response
Relevant log output
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Starting from V5, the resolver automatically infers types from the schema, so you no longer need to specify them manually. You can remove <FormValues> from useForm.
@jorisre Thank you for your response.
I have confirmed that deleting <FormValues> will fixes the error. (line 28 of codesandbox)
How can I use this with defaultValues prop?
I get an error if I don't pass all type parameters for useForm. (line 43, 49 of codesandbox)
I find this inconvenient, is there a workaround?
Could you clarify what you need? I'm not quite sure I understand your goal.
-
Removing the useForm type parameter still results in a type error.
- Occurs when
defaultValuesis receive as props. - (Edited codesandbox): See line 43 of src/App.tsx.
- Occurs when
📝 NOTE Probably because of the mismatch between the inferred Input and Output types in the case of a schema with optional fields. https://github.com/react-hook-form/resolvers/blob/6e8839343dcfea0fe9b874772a01f3bc551cbb5c/yup/src/yup.ts#L54
Taking the codesandbox code as an example,
- Input ->
{ hoge: string | undefined } - Yup.InferType<typeof schema> ->
{ hoge?: string | undefined }
Starting from V5, the resolver automatically infers types from the schema, so you no longer need to specify them manually. You can remove
<FormValues>fromuseForm.
this behavior fails in recent Zod v4
@Yama-Tomo : I fixed your code sandbox
https://codesandbox.io/p/sandbox/react-hook-form-resolver-issue-forked-d4qt4c
You can't use defaultValues via component properties and use the schema from outside. The type is more complex here. The best way is to inject the schema via component properties, too. Then the type is correct.
My workaround was to create a wrapper for yupResolver and respect the useForm type parameter.
(Edited codesandbox: line 105 of src/App.tsx)
We have same type error now when using defaultValues.
It does not seem right using workarounds in our end to make built in react-hook-forms functionality (defaultValues) and library from same creators (@hookform/resolvers) work together.