Skip to content

Commit a61f352

Browse files
committed
Changed 74 solution
1 parent d9ee27e commit a61f352

File tree

2 files changed

+61
-9
lines changed

2 files changed

+61
-9
lines changed

src/09-external-libraries/74-react-hook-form-wrapper.solution.tsx renamed to src/09-external-libraries/74-react-hook-form-wrapper.solution.1.tsx

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,8 @@
11
import { DefaultValues, FieldValues, useForm } from "react-hook-form";
22
import { Equal, Expect, Extends } from "../helpers/type-utils";
33

4-
/**
5-
* We add TValues as a generic to our hook, and use it to type the defaultValues.
6-
*
7-
* We constrain it to FieldValues so that it's assignable to useForm's defaultValues.
8-
*/
94
const useCustomForm = <TValues extends FieldValues>(defaultValues: TValues) => {
105
const form = useForm({
11-
/**
12-
* There's a strange papercut here where we have to cast defaultValues as
13-
* DefaultValues<TValues> to get it to work.
14-
*/
156
defaultValues: defaultValues as DefaultValues<TValues>,
167
});
178

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import {
2+
DefaultValues,
3+
FieldValues,
4+
UseFormGetValues,
5+
UseFormHandleSubmit,
6+
UseFormRegister,
7+
useForm,
8+
} from "react-hook-form";
9+
import { Equal, Expect, Extends } from "../helpers/type-utils";
10+
11+
const useCustomForm = <TValues extends FieldValues>(
12+
defaultValues: TValues,
13+
): {
14+
register: UseFormRegister<TValues>;
15+
handleSubmit: UseFormHandleSubmit<TValues>;
16+
getValues: UseFormGetValues<TValues>;
17+
} => {
18+
const form = useForm({
19+
defaultValues: defaultValues as DefaultValues<TValues>,
20+
});
21+
22+
return {
23+
register: form.register,
24+
handleSubmit: form.handleSubmit,
25+
getValues: form.getValues,
26+
};
27+
};
28+
29+
// ---- TESTS ----
30+
31+
// @ts-expect-error defaultValues is required
32+
useCustomForm();
33+
34+
useCustomForm(
35+
// @ts-expect-error defaultValues must be an object
36+
2,
37+
);
38+
39+
const customForm = useCustomForm({
40+
firstName: "",
41+
lastName: "",
42+
});
43+
44+
customForm.handleSubmit((values) => {
45+
type test = Expect<
46+
// Expect that inside handleSubmit, it's inferred as
47+
// { firstName: string; lastName: string }
48+
Extends<
49+
{
50+
firstName: string;
51+
lastName: string;
52+
},
53+
typeof values
54+
>
55+
>;
56+
});
57+
58+
// Expect that only the methods we want are exposed
59+
type test = Expect<
60+
Equal<keyof typeof customForm, "register" | "handleSubmit" | "getValues">
61+
>;

0 commit comments

Comments
 (0)