feat(forms): Implement strong types for the Angular Forms package. #43834
+1,743
−387
Conversation
This PR strongly types the forms package by adding generics to `AbstractControl` classes as well as `FormBuilder`. This makes forms type-safe and null-safe, for both controls and values. The design uses a "control-types" approach. In other words, the type parameter on `FormGroup` is an object containing controls, and the type parameter on `FormArray` is an array of controls. **BREAKING CHANGE:** This adds generics to several forms APIs, including the `AbstractControl` classes and `FormBuilder`, and could break any usages that have not been migrated. In order to return to the old behavior, provide an explicit `any`, or `any[]` in the case of `FormArray`. For example, `let c = new FormControl<any>(42);` or `let a = new FormArray<any[]>([2, 4, 6]);`. Issue: angular#13721
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.


Summary
This PR strongly types the forms package by adding generics to
AbstractControlclasses as well asFormBuilder. This makes forms type-safe and null-safe, for both controls and values.The design uses a "control-types" approach. In other words, the type parameter on
FormGroupis an object containing controls, and the type parameter onFormArrayis an array of controls.BREAKING CHANGE: This adds generics to several forms APIs, including the
AbstractControlclasses andFormBuilder, and could break any usages that have not been migrated. In order to return to the old behavior, provide an explicitany, orany[]in the case ofFormArray.Some examples of using
anyto migrate existing code:let c = new FormControl<any>(42);let a = new FormArray<any[]>([2, 4, 6]);.let g = new FormGroup<any>({c: new FormControl<any>(42)});.let someControl: AbstractControl<any>new FormBuilder().control<any>('foo');Issue: #13721
PR Status
Typed Forms is currently wrapping up the exploratory phase, and we now have a solid understanding of the main tradeoffs. This PR appears to work and represents the choices I think are ideal. However, the design is not final, and we will likely discover bugs during the google3 migration process.
In particular, here is some of the remaining work:
FormTupleandFormRecordclasses could be useful -- this needs an RFC and more design.AbstractControlclasses, such asValidatorsandControlValueAccessor, may or may not be included in this project. This adds a lot of scope and risk, and should be discussed in the RFC.I'm currently targeting Angular v14. This PR is a draft and is not ready for final merge review.
Background
For five years, users have been requesting strong types on Forms. The Github Issue (#13721) is the number one most popular issue of all time on the Angular repo, with around 1k reactions and hundreds of comments.
Several contributors have attempted to implement typed forms. The most complete prior implementation is #38406 by @sonukapoor. Other attempts include #16828 and #20040 by @Toxicable, #37389 by @KostyaTretyak, #38906 by @MBuchalik, as well as #40772 by @MikeJerred. There are also several wrapper implementations inside google3. We didn't merge these PRs due to various issues, mostly pertaining to type soundness and google3 backwards-compatibility. (However, I have read and learned from them extensively -- special thanks to the authors of these PRs.)
Motivation
Consider the following schema representing a party:
In the current version of Angular Forms, we can construct a corresponding form. This form represents a default party at
1234 Main Stwhich is not formal, and has no food options:Now let's try to read our form's value. As you can see, we frequently get values of type
anywhen dealing with our form. This issue is pervasive across the entire Forms API:However, with this implementation of typed forms, the types are highly specific and far more helpful:
Additionally, the current API is very unsafe. Any control can be set to a value with an incorrect type, as in the following:
This illustrates the purpose of typed forms: the API now reflects the structure of the form and its data, even for very complex nested forms.
Away From a New API
The first and most obvious design question is whether to add generics to the existing API, wrap it with a typed layer, or create an entirely new API. There are a few dominant considerations:
FormGroups should accept untypedFormArrays as members, and vice-versa.These concerns immediately rule out creating an entirely new API: in order to beat fragmentation, we want to provide an automatic migration. That means the new API would need to map cleanly onto the old one. In that case, there is no real design benefit of doing a rewrite. (Note, however, that the presence of strong types would potentially make a future Forms 2.0 an easier migration, after they are widely adopted.)
Adding new wrapper classes will result in a huge number of permutations of ways that typed and untyped classes can be nested in a complex form. This makes the compatibility issue quite difficult; better to add types to the existing classes, if possible.
Finally, the rollout strategy points strongly towards adding types to the existing classes. This is mostly google3-internal and documented elsewhere, but is a major consideration.
Value Types and Control Types
A key design question involves whether to use value types or control types for the new type parameters. With the former, the type of a control is the inner controls; with the latter, the type of a control is the values of the inner controls. In other words, the generic can either have the type of the value accessor, or the type of the controls accessor.
In the below example, an address has a house number and a street name. I explicitly specify the type parameter to illustrate the difference:
I implemented prototypes using both of these approaches. There are several advantages to using value types. The most significant is that client code can re-use existing interfaces:
However, there is a major disadvantage of using value types. In cases involving nested FormGroups, type information about the inner objects is lost. Consider:
We will treat
gas anAbstractControlwith an object value when using this construction. However, this introduces an ambiguity: most commonly g will be aFormGroup, but it could also be a customFormControlwith an object value! It is not possible to resolve this ambiguity because the concrete type information is lost. Even worse, it is entirely possible that a customFormControlhas nested objects in its value, which are also impossible to disambiguate.The above issue leads directly to the following gotcha:
This is the same concrete type as above, except for the assertion that the inner group is optional. However, when setting and consuming this value later, it is impossible to know whether g is an optional group, or whether it is an object with optional keys. Thus, the following is an error:
In contrast with value types, control types require client code to wrap existing interfaces to use those interfaces as a type parameter:
However, it should be possible to use a mapped type to eliminate the need to manually specify the controls interface in most cases:
Note that
InferControlTypeswould make assumptions that are not generally true (e.g. object-valued subfields areFormGroups). Thus, in some cases involving custom-valuedFormControls, the mapped type helper cannot be used. However, it should be helpful in most cases. The exact design and implementation ofInferControlTypesshould be discussed in the RFC.Given the limitations on value types described above, this prototype uses control types.
Disabled Controls and
PartialvaluesThe
.valueof aFormGroupdoes not always give all the group's properties. Specifically, if any inner control is disabled, it will be excluded from the value. (The original reason for this strange behavior is that HTML web forms work similarly, with disabled controls excluded.) In this example, a patient has a name and a condition, but the condition field has been disabled for HIPPA compliance reasons:Thus, the proper type of
patient.valueisn't the full object; it's aPartialof the object. In this case, the type ofpatient.valueisPartial<{name: string, condition: string}>.Some APIs use the complete value, whereas other APIs use the partial value:
.value.getRawValue().patchValue(...).setValue(...)Imagine a form has multiple nested groups. It's not enough to simply define the type of
valueto be aPartial, because the partiality applies recursively to allFormGroups in the tree of controls. What are the correct types forc.setValue(...)andc.patchValue(...)in this case?c.setValuerequires all properties to be present. However,c.patchValueaccepts deeply partial objects. The shapes of the required arguments are as below:There are several ways to apply this
Partialobject recursively. In this implementation, we giveAbstractControltwo type parameters: the first is the partial value type, and the second is the complete value type. That way, these two types can be used for the differing signatures of the above APIs.Alternative methods of implementing this also exist: specifically, it is possible to build a recursive type that calculates the partial values explicitly.
(Note that this is also another strike against using value types: with value types, it is impossible to disambiguate an object that came from a FormGroup from an object in a custom FormControl.)
Nullable Controls and
reset()The issue of when
reset()can be called, and with what arguments, is far more complex than it first appears.Consider the following vexing example:
Clearly, we'd like
foods.valueto have typestring[]. However,.reset()will cause the value to be[null, null], which would violate that type contract. Analogous issues also exist forFormGroupandFormControl:I tried implementing four possible solutions, each with its own tradeoffs:
FormControls are implicitly nullable. This means thatnew FormControl('foo')would have typestring|null.resetmethod requires non-nullable controls to be provided as an argument. In thecontactexample above,resetwould require an argument with thenameproperty, but not necessarily the nullableageproperty.reset()can be called with no arguments, easing migration.FormGroup's type, arbitrarily many levels down.FormArray, because the type system cannot know how many elements are in the array, and whether the argument toresetis complete. This is can be worked around forreadonlyarrays (i.e. tuples), but never for mutable arrays.resetmethod requires all controls to be provided as an argument. In thecontactexample above, the full object must be provided, with bothnameandage.reset()will be incompatible with typed forms, requiring a large effort to migrate them eventually.FormArrays, since we can't know how many elements are in the array. However, there are workarounds, such as requiring a single default element that can be used at all positions. However, that doesn't match the semantic behavior most users will actually want.FormControltakes an optional default value at the time it is constructed. If a default value is provided then the control resets to that value; otherwise, the control is implicitly nullable, and will reset tonull.FormControlis different: it's no longer guaranteed thatreset()will make a controlnull. This isn't obviously an issue for backwards-compatibility, but any change to such important runtime behavior is risky.FormControlgets a second constructor signature, and there's no obviously great place to put the new argument. This could be improved with more work, but never totally eliminated.FormBuildera great API for non-nullable controls, since control values are often provided as naked literals (e.g.fb.array([1, 2, 3])).Option 1 is undesirable because, as mentioned above, it would defeat much of the benefit of the project. Options 2 and 3 suffer from the same show-stopping problem involving
FormArray.reset()being unsound. That leaves option 4, which has some tradeoffs aroundFormBuilder, but is otherwise reasonable.(Note: it would be nice to put the default value before the two optional validator arguments, but this is quite tricky in practice due to existing callers. We should consider fixing it with a schematic. This could also be fixed with a schematic at a future date.)
Optional Controls and Index Signatures
FormGroupprovides two APIs that encourage very dynamic use:addControl()andremoveControl(). This hints at an underlying paradox ofFormGroup. It is one class that serves two different purposes:FormArraywith named controls. The controls are not all known ahead of time.An example of the first use case, in which the shape of the object is known, would be an item on a menu. Here, we require the item have a named food, but the price is an optional property -- by removing it, we might indicate the food is free:
Trying to call
removeControl('food')will result in an error, since that property is not optional.The second use case would be something like a phone book. This phone book has a spot for the owner's number, but after that, the properties are unknown. We can represent them using an index signature:
Notice that in both of these cases, we had to explicitly provide a type for the
FormGroupinside the angle brackets. That's because, without providing it, the simplest possible type will be inferred. The inferred type will never include an optional property or an index signature.An alternative design is possible, in which index signatures wouldn't be supported, and an open-ended group would be an entirely different class. Perhaps we would call that class
FormRecord:Notice that no explicit type was required, since every
FormRecordwould implicitly be open-ended. Whether we should stick with the current approach or add aFormRecordtype is a major open question for the RFC.Heterogenous Arrays and
FormTupleMutable arrays should typically be homogenous. Trying to construct the following array would be an error, and rightly so, as it's not clear what the value type of an element should be:
It is possible to "force" this to work by explicitly making each control accept the union of all value types in the array. However, it's not very useful:
We intend to add a brand new class called
FormTuple. Tuples are constant arrays, from which elements can never be added or removed. That means we could have the following:The type system is aware of what type is at each position in the tuple, since the tuple is constant. More design work for
FormTupleis required.Examples
Here are some simple examples. The APIs are largely the same as before, but with added type information!
FormControlFormGroupFormArrayFormBuilderThe text was updated successfully, but these errors were encountered: