11import { FieldValues , useForm } from "react-hook-form" ;
22import { Equal , Expect } from "../helpers/type-utils" ;
33
4+ /**
5+ * 1. When you provide default values to useForm, the return type of getValues
6+ * gets inferred as the shape of those values.
7+ *
8+ * Investigate why this is, and what TFieldValues is being used for.
9+ */
410const Example1 = ( ) => {
511 const form = useForm ( {
6- values : {
12+ defaultValues : {
713 firstName : "" ,
814 lastName : "" ,
915 } ,
@@ -23,6 +29,13 @@ const Example1 = () => {
2329 ) ;
2430} ;
2531
32+ /**
33+ * 2. When you don't pass a default value, the return type of getValues is
34+ * inferred as FieldValues.
35+ *
36+ * Investigate why this is, and what type FieldValues is.
37+ */
38+
2639const Example2 = ( ) => {
2740 const form = useForm ( ) ;
2841
@@ -37,3 +50,30 @@ const Example2 = () => {
3750 </ form >
3851 ) ;
3952} ;
53+
54+ /**
55+ * 3. If we don't pass default values, how do we get
56+ * react-hook-form to understand what type our fields are?
57+ */
58+
59+ type FormValues = {
60+ firstName : string ;
61+ lastName : string ;
62+ } ;
63+
64+ const Example3 = ( ) => {
65+ const form = useForm < FormValues > ( ) ;
66+
67+ return (
68+ < form
69+ onSubmit = { form . handleSubmit ( ( values ) => {
70+ type test = Expect < Equal < typeof values , FormValues > > ;
71+ } ) }
72+ >
73+ < input { ...form . register ( "firstName" ) } />
74+ < input { ...form . register ( "lastName" ) } />
75+ { /* @ts -expect-error */ }
76+ < input { ...form . register ( "middleName" ) } />
77+ </ form >
78+ ) ;
79+ } ;
0 commit comments