Skip to content

Commit 676b630

Browse files
committed
WIP
1 parent 21047ab commit 676b630

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

src/09-external-libraries/73-react-hook-form.problem.tsx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,30 @@ const Example2 = () => {
5050
</form>
5151
);
5252
};
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();
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+
};

src/09-external-libraries/73-react-hook-form.solution.tsx

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
import { FieldValues, useForm } from "react-hook-form";
22
import { 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+
*/
410
const 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+
2639
const 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

Comments
 (0)