Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

useField.test-d.tsx

109 lines2.3 KB

1import { expectTypeOf, it } from 'vitest'
2import { useForm } from '../src/index'
3​
4it('should type state.value properly', () => {
5 function Comp() {
6 const form = useForm({
7 defaultValues: {
8 firstName: 'test',
9 age: 84,
10 },
11 } as const)
12​
13 return (
14 <>
15 <form.Field
16 name="firstName"
17 children={(field) => {
18 expectTypeOf(field.state.value).toEqualTypeOf<'test'>()
19 return null
20 }}
21 />
22 <form.Field
23 name="age"
24 children={(field) => {
25 expectTypeOf(field.state.value).toEqualTypeOf<84>()
26 return null
27 }}
28 />
29 </>
30 )
31 }
32})
33​
34it('should type onChange properly', () => {
35 function Comp() {
36 const form = useForm({
37 defaultValues: {
38 firstName: 'test',
39 age: 84,
40 },
41 } as const)
42​
43 return (
44 <>
45 <form.Field
46 name="firstName"
47 validators={{
48 onChange: ({ value }) => {
49 expectTypeOf(value).toEqualTypeOf<'test'>()
50 return null
51 },
52 }}
53 children={() => null}
54 />
55 <form.Field
56 name="age"
57 validators={{
58 onChange: ({ value }) => {
59 expectTypeOf(value).toEqualTypeOf<84>()
60 return null
61 },
62 }}
63 children={() => null}
64 />
65 </>
66 )
67 }
68})
69​
70it('should type array subfields', () => {
71 type FormDefinition = {
72 nested: {
73 people: {
74 name: string
75 age: number
76 }[]
77 }
78 }
79​
80 function App() {
81 const form = useForm({
82 defaultValues: {
83 nested: {
84 people: [],
85 },
86 } as FormDefinition,
87 onSubmit({ value }) {
88 alert(JSON.stringify(value))
89 },
90 })
91​
92 return (
93 <form.Field name="nested.people" mode="array">
94 {(field) =>
95 field.state.value.map((_, i) => (
96 <form.Field key={i} name={`nested.people[${i}].name`}>
97 {(subField) => (
98 <input
99 value={subField.state.value}
100 onChange={(e) => subField.handleChange(e.target.value)}
101 />
102 )}
103 </form.Field>
104 ))
105 }
106 </form.Field>
107 )
108 }
109})