Type Inference Problem with useController in React Hook Form #12669
Unanswered
PrinceHirani9
asked this question in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I am using react-hook-form with Zod validation and trying to make my custom hook useDragItems generic. The goal is to pass a control and a name (path to a field in the form) dynamically while maintaining proper TypeScript inference. However, useController does not correctly infer the field type, and I encounter the following error:
Error message
Form types
Common types
Custom Hook
useDragItems
Problem Explanation
useControlle
r hook should infer the correct type from name, but instead, value is inferred asPathValue<T, Path<T>>
, which does not automatically resolve to Team[].val
invalue.some((val) => val.role === teamRole)
is implicitlyany
, causing a TypeScript error.name
is"teams"
,value
should be inferred as Team[], but TypeScript does not resolve this correctly.Why This Needs to Be Generic
"teams"
. It is meant to be used in multiple places with different form structures and field names.name
, ensuring that the correct type is inferred dynamically.Attempted Workarounds
useController<FormValues, "teams">({ control, name })
value as Team[]
, which works but is not idealExpected Behavior
useController
should infer the correct type fromname
, sovalue
should automatically beTeam[]
whenname
is"teams"
.value.some((val) => val.role === teamRole)
without TypeScript errors.Question
How can I ensure that
useController
infers the correct type forvalue
based on thename
path without needing type assertions? Is there a recommended approach to handle this issue in a generic way? Also please let me know if I am going in the right direction or not.Beta Was this translation helpful? Give feedback.
All reactions