useFieldArray (and useController) should allow specifying value type constraints
See original GitHub issueIs your feature request related to a problem? Please describe.
In our project we have several different forms which have a field represented by an array of objects with specific type.
We have created a reusable React component to edit this arrays, basically a custom field (in abstract sense).
This component accepts control
and name
properties and uses useFieldArray
.
Because this component is generic, we can not infer the value type from FieldValues
since the specific schema of FieldValues
is unknown at that point.
But our component expects fields
returned from useFieldArray
to have specific type.
Currently typings in react-hook-form
do not provide sufficient capabilities, and we have to rely on manual type casting via field as unknown as MyType
.
Note that this is only a type system problem, javascript code works fine.
See the example in CodeSandbox
This problem also arises for simple custom fields when we use useController
hook.
For example, if we have a custom text field, we would like to restrict value type to be string
.
useController exampe in CodeSandbox
Describe the solution you’d like The solution I envision consists of two parts:
- We need to allow specifying type constraints in
FieldArrayPath
andFieldPath
so that when defining custom field components we could restrictTFieldArrayName
andTFieldName
to extract only those paths which have the desired type. This would allow for type safety for users of our custom field component in concrete forms. - Hooks
useFieldArray
anduseController
should allow for custom type specification for cases where concrete shape ofFieldValues
is unknown. This could be a third type argument which defaults toFieldArrayWithId
/PathValue
. This would allow for type safety inside our custom field component.
These two parts work together to ensure complete type safety given that we correctly specify the same custom type constraint in both of them.
If we only have the first part of the solution, typescript is not smart enough to extract the correct value type when using the useFieldArray
or useController
hooks.
Here is the CodeSandbox with some of the library types changed which kinda shows the complete solution: https://codesandbox.io/s/react-hook-form-use-controller-generic-33yo5
Describe alternatives you’ve considered
No other API in react-hook-form
seems to provide the desired functionality for custom field components.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:13
- Comments:6 (3 by maintainers)
Top GitHub Comments
will resolve and improve this in v8
https://github.com/react-hook-form/react-hook-form/discussions/7354
Wow, that’s some great news! Looking forward to trying this feature! 9 окт. 2021 г., 09:34 +0300, Bill @.***>, писал: