-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypedForms.ts
114 lines (106 loc) · 2.27 KB
/
TypedForms.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { FormArray, FormControl, FormGroup } from "@angular/forms";
/**
* Built-in type that is not an object.
*/
export type Primitive =
| null
| undefined
| string
| number
| boolean
| symbol
| bigint;
/**
* Built-in type that is not a collection.
*/
export type BuiltIn = Date | Primitive | RegExp;
/**
* Makes properties of T optional.
* If the property has an object type, makes it `Partial<TProp>`.
*/
export type DeepPartial<T> = T extends BuiltIn
? T
: T extends object
? { [P in keyof T]?: DeepPartial<T[P]>; }
: T;
/**
* Unwraps the properties of a form to their underlying types.
*
* for example:
* ```ts
* interface MyForm
* {
* a: FormControl<string>;
* b: FormGroup<MySubForm>;
* c: FormArray<FormGroup<FormItem>;
* }
* ```
* becomes:
* ```ts
* interface _MyForm {
* a: string;
* b: _MySubForm;
* c: _FormItem[];
* }
* ```
*
* Use this when declaring functions working with form values, for example:
* ```ts
* function doStuff(frmValue: FormValue<MyForm>): void {
* console.log(frmValue.a)
* }
* ///...
* doStuff(frm.getRawValue())
* ```
*/
export type FormValue<T> = {
[K in keyof T]: T[K] extends FormControl<infer value>
? value
: T[K] extends FormGroup
? FormGroupValue<T[K]>
: T[K] extends FormArray
? FormArrayValue<T[K]>
: T[K]
}
/**
* Unwraps the properties of a form to their underlying types and makes properties optional.
*
* Use this when working with patchValue or form.value,
* for example:
* ```ts
* ///...
* const update: PartialFormValue<MyForm> = {
* a: "xyz"
* };
* frm.patchValue(update)
* ```
*/
export type PartialFormValue<T> = DeepPartial<FormValue<T>>
/**
* Type of the underlying value of a FormGroup.
*
* ```ts
* FormGroupValue<FormGroup<MyForm>>
* ```
* Is equivalent to:
* ```ts
* FormValue<MyForm>;
* ```
*/
export type FormGroupValue<T> = T extends FormGroup<infer U>
? FormValue<U>
: T
/**
* Type of the underlying value of a FormArray.
*
* ```ts
* FormArrayValue<FormArray<FormGroup<MyForm>>>
* ```
* Is equivalent to
* ```ts
* Array<FormValue<MyForm>>
* ```
*/
export type FormArrayValue<T> = T extends FormArray<infer U>
? Array<FormGroupValue<U>>
: T