Visitar URL original
feat(forms): Implement strong types for the Angular Forms package. by dylhunn · Pull Request #43834 · angular/angular · GitHub
The Wayback Machine - https://web.archive.org/web/20211014121912/https://github.com/angular/angular/pull/43834
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(forms): Implement strong types for the Angular Forms package. #43834

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

@dylhunn
Copy link
Contributor

@dylhunn dylhunn commented Oct 14, 2021 •

Summary

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.

Some examples of using any to 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:

  1. We will publish an official RFC to discuss and improve the design.
  2. New FormTuple and FormRecord classes could be useful -- this needs an RFC and more design.
  3. Typing non-AbstractControl classes, such as Validators and ControlValueAccessor, may or may not be included in this project. This adds a lot of scope and risk, and should be discussed in the RFC.
  4. We will write a schematic to allow for non-breaking migrations.
  5. Google3 must be assessed for readiness and then migrated according to the schematic.
  6. Docs must be updated.

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:

type Party = {
  address: {
    number: number,
    street: string,
  },
  formal: boolean,
  foodOptions: Array<{
    food: string,
    price: number,
  }>
}

In the current version of Angular Forms, we can construct a corresponding form. This form represents a default party at 1234 Main St which is not formal, and has no food options:

const partyForm = new FormGroup({
  address: new FormGroup({number: new FormControl(1234), street: new FormControl('Main St')}),
  formal: new FormControl(false),
  foodOptions: new FormArray([])
});

Now let's try to read our form's value. As you can see, we frequently get values of type any when dealing with our form. This issue is pervasive across the entire Forms API:

const partyDetails = partyForm.getRawValue(); // type `any`
const where = partyForm.get('address.street')!.value; // type `any`

However, with this implementation of typed forms, the types are highly specific and far more helpful:

const partyDetails = partyForm.getRawValue(); // same type as `Party`
const where = partyForm.get('address.street')!.value; // type `string`

Additionally, the current API is very unsafe. Any control can be set to a value with an incorrect type, as in the following:

const theGoodWitch = new FormControl('Glinda'); // This control is expected to have a name.
theGoodWitch.setValue(42); // Oops! This should be an error.

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:

  • No long-term fragmentation. We consider not fragmenting the ecosystem a hard requirement -- we don't want two incompatible versions of Forms to be in use indefinitely.
  • Inter-compatible Typed and Untyped Forms. Many Angular apps have very large, complex forms, which will be difficult and time-consuming to completely type. Moreover, some forms are naturally heterogenous in a way that makes them impossible to type. As such, it should be possible to get some benefit without having to type an entire Forms application. This means that, for example, typed FormGroups should accept untyped FormArrays as members, and vice-versa.
  • Easy rollout strategy: we need to roll out the new library with a migration both internally (google3) and externally (v14). We should be able to do this safely in a minimal number of steps.

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:

// Value types. The type parameter is an object with a number and a string.
const address = new FormGroup<{number: number, street: string}>(
    {number: new FormControl(1234), street: new FormControl('Geary St')});

// Control types. The type parameter is an object with two FormControls, one with a number and one with a string.
const address = new FormGroup<{number: FormControl<number>, street: FormControl<string>}>(
    {number: new FormControl(1234), street: new FormControl('Geary St')});

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:

interface Person {
    name: string;
}

let fg: FormGroup<Person>;

However, there is a major disadvantage of using value types. In cases involving nested FormGroups, type information about the inner objects is lost. Consider:

const c = new FormGroup({g: new FormGroup({c: new FormControl('')})});

We will treat g as an AbstractControl with an object value when using this construction. However, this introduces an ambiguity: most commonly g will be a FormGroup, but it could also be a custom FormControl with 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 custom FormControl has nested objects in its value, which are also impossible to disambiguate.

The above issue leads directly to the following gotcha:

const c = new FormGroup<{g?: {c: string}}>({g: new FormGroup({c: new FormControl('')})});

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:

c.addControl('g', new FormGroup({c: new FormControl('')}));

In contrast with value types, control types require client code to wrap existing interfaces to use those interfaces as a type parameter:

interface Person {
    name: string;
}

interface PersonControls {
    name: FormControl<string>;
}

let fg: FormGroup<PersonControls>;

However, it should be possible to use a mapped type to eliminate the need to manually specify the controls interface in most cases:

let fg: FormGroup<InferControlTypes<Person>>;

Note that InferControlTypes would make assumptions that are not generally true (e.g. object-valued subfields are FormGroups). Thus, in some cases involving custom-valued FormControls, the mapped type helper cannot be used. However, it should be helpful in most cases. The exact design and implementation of InferControlTypes should be discussed in the RFC.

Given the limitations on value types described above, this prototype uses control types.

Disabled Controls and Partial values

The .value of a FormGroup does 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:

const patient = new FormGroup({
  name: new FormControl('Bob'),
  condition: new FormControl({value: '', disabled: true}),
});
const val = patient.value;  // {name: 'Bob'}

Thus, the proper type of patient.value isn't the full object; it's a Partial of the object. In this case, the type of patient.value is Partial<{name: string, condition: string}>.

Some APIs use the complete value, whereas other APIs use the partial value:

Partial Values Complete Values
.value .getRawValue()
.patchValue(...) .setValue(...)

Imagine a form has multiple nested groups. It's not enough to simply define the type of value to be a Partial, because the partiality applies recursively to all FormGroups in the tree of controls. What are the correct types for c.setValue(...) and c.patchValue(...) in this case?

const c = new FormGroup({g: new FormGroup({c: new FormControl('')})});

c.setValue requires all properties to be present. However, c.patchValue accepts deeply partial objects. The shapes of the required arguments are as below:

// setValue takes a complete object
{
  g: {
    c: '';
  }
}

// patchValue takes an object where all nested objects are Partials
Partial<{
  g: Partial<{
    c: '';
  }>
}>

There are several ways to apply this Partial object recursively. In this implementation, we give AbstractControl two 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:

const foods = new FormArray([new FormControl('ravioli'), new FormControl('injera')]);
foods.reset();
const value = foods.value; // [null, null]

Clearly, we'd like foods.value to have type string[]. However, .reset() will cause the value to be [null, null], which would violate that type contract. Analogous issues also exist for FormGroup and FormControl:

const hashtag = new FormControl('#FreeBritney');
hashtag.reset();
const hashtagValue = hashtag.value; // null

const contact = new FormGroup({name: new FormControl('Alex'), age: new FormControl<number|null>(29)});
contact.reset();
const contactValue = contact.getRawValue(); // {name: null, age: null}

I tried implementing four possible solutions, each with its own tradeoffs:

  1. All FormControls are implicitly nullable. This means that new FormControl('foo') would have type string|null.
    • Pro: this completely solves the above issue by simply making it legal.
    • Pro: this is extremely easy to implement.
    • Con: typed forms will never be null-safe, defeating much of this project's purpose.
  2. The reset method requires non-nullable controls to be provided as an argument. In the contact example above, reset would require an argument with the name property, but not necessarily the nullable age property.
    • Pro: all controls are null safe to the maximum extent possible.
    • Pro: incomplete objects can be provided, containing any number of keys between the minimum required and the maximum possible.
    • Pro: on a fully nullable control, reset() can be called with no arguments, easing migration.
    • Con: the implementation is horrific. Although I did successfully implement this, it requires recursively introspecting a FormGroup's type, arbitrarily many levels down.
    • Con: the error messages are awful for various implementation-related reasons.
    • Con: it's impossible to fully handle FormArray, because the type system cannot know how many elements are in the array, and whether the argument to reset is complete. This is can be worked around for readonly arrays (i.e. tuples), but never for mutable arrays.
    • Con: the difference between nullable and optional controls is subtle, confusing, and extremely important.
  3. The reset method requires all controls to be provided as an argument. In the contact example above, the full object must be provided, with both name and age.
    • Pro: quite a bit easier to implement than only requiring nullable controls.
    • Pro: no confusion between optional and nullable controls, since all controls are always required.
    • Con: for deeply nested forms, the required argument could be very large and error-prone.
    • Con: all existing calls to nullary reset() will be incompatible with typed forms, requiring a large effort to migrate them eventually.
    • Con: still cannot handle mutable 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.
  4. FormControl takes 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 to null.
    • Pro: a beautiful solution that allows developers to choose whether they want nullability for each control individually.
    • Pro: very easy to implement and understand.
    • Con: the runtime behavior of FormControl is different: it's no longer guaranteed that reset() will make a control null. This isn't obviously an issue for backwards-compatibility, but any change to such important runtime behavior is risky.
    • Con: FormControl gets 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.
    • Con: It's difficult to give FormBuilder a 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 around FormBuilder, but is otherwise reasonable.

const foods = new FormArray([
  // Each control gets a value, undefined for its validators, and '' as a default value.
  new FormControl('ravioli', undefined, undefined, ''),
  new FormControl('injera', undefined, undefined, '')
]);

foods.reset();
const value = foods.value;  // ['', '']

(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

FormGroup provides two APIs that encourage very dynamic use: addControl() and removeControl(). This hints at an underlying paradox of FormGroup. It is one class that serves two different purposes:

  1. A known collection of named child controls. Some controls are optional and can be removed, but they are logically all enumerated ahead of time.
  2. A dynamic collection of controls, much like a version of FormArray with 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:

// A menu item always has a food, but the price is optional (it might be free).
const menuItem = new FormGroup<{food: FormControl<string>, price?: FormControl<number>}>({
  food: new FormControl('tofu', undefined, undefined, ''),
  price: new FormControl(10, undefined, undefined, 10),
});

menuItem.removeControl('price');

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:

// A phone book has an owner's phone number, but then it has an unlimited number of other entries.
const phoneBook = new FormGroup<{
  Owner: FormControl<string>,
  [name: string]: FormControl<string>,
}>({
  Owner: new FormControl('214-456-7890', undefined, undefined, ''),
  Jess: new FormControl('469-456-7890', undefined, undefined, ''),
});

phoneBook.addControl('Kristiyan', new FormControl('123-465-3231', undefined, undefined, ''));
phoneBook.removeControl('Kristiyan');

Notice that in both of these cases, we had to explicitly provide a type for the FormGroup inside 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:

const phoneBook = new FormRecord({
  Owner: new FormControl('214-456-7890', undefined, undefined, ''),
  Jess: new FormControl('469-456-7890', undefined, undefined, ''),
});

phoneBook.addControl('Kristiyan', new FormControl('123-465-3231', undefined, undefined, ''));
phoneBook.removeControl('Kristiyan');

Notice that no explicit type was required, since every FormRecord would implicitly be open-ended. Whether we should stick with the current approach or add a FormRecord type is a major open question for the RFC.

Heterogenous Arrays and FormTuple

Mutable 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:

const ecclectic = new FormArray([new FormControl('potato'), new FormControl(6)]); // Error!

ecclectic.push( ... ); // What should the parameter type be?
const value = ecclectic.value[0]; // What should the type 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:

const ecclectic = new FormArray([
  new FormControl<string|number|boolean>('potato'),
  new FormControl<string|number|boolean>(6),
  new FormControl<string|number|boolean>(true)
]);

ecclectic.push( ... ); // Takes FormControl<string|number|boolean|null>
const useless = ecclectic.value[0]; // string|number|boolean|null

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:

const collection = new FormTuple([new FormControl('potato'), new FormControl(6)]);

const produce = collection.value[0]; // string
const rating = collection.value[1]; // number

The type system is aware of what type is at each position in the tuple, since the tuple is constant. More design work for FormTuple is required.

Examples

Here are some simple examples. The APIs are largely the same as before, but with added type information!

FormControl

// An untyped `FormControl`.
const username0 = new FormControl<any>('Bob');
let who = username1.value;  // 'Bob', type is `any`
// A `FormControl<string>` which is required, and defaults to 'username' when reset.
const username1 = new FormControl('Bob', Validators.required, undefined, 'username');
let who = username1.value;  // 'Bob', type is `string`
username1.reset();
who = username1.value;  // ''
// A `FormControl<string|null>` which defaults to null when reset.
const username2 = new FormControl('Bob');
let who2 = username2.value;  // 'Bob', type is `string|null`
username2.reset();
who2 = username2.value;  // null

FormGroup

// A cat has 9 lives to start with.
const cat = new FormGroup({lives: new FormControl(9)});

cat.setControl('lives', new FormControl(6));
const hasLives = cat.contains('lives'); // true, type boolean
cat.setValue({lives: 0});
cat.patchValue({});
cat.reset({lives: 0}); // Reset using a specific value

FormArray

// An array of lucky numbers.
const lucky = new FormArray([new FormControl(7), new FormControl(42)]);

const firstLucky = lucky.value[0]; // 7, has type number

// Add 101 to the lucky numbers.
lucky.push(new FormControl(101));
// An array of dinner choices for a party. Each choice has an entree and desert, plus a price.
const dinnerOptions = new FormArray([
  // Dinner choice one
  new FormGroup({
    food: new FormGroup({
      entree: new FormControl('Baked Tofu', undefined, undefined, ''),
      dessert: new FormControl('Cheesecake', undefined, undefined, ''),
    }),
    price: new FormControl(10, undefined, undefined, 0),
  }),
  // Dinner choice two
  new FormGroup({
    food: new FormGroup({
      entree: new FormControl('Eggplant Parm', undefined, undefined, ''),
      dessert: new FormControl('Chocolate Mousse', undefined, undefined, ''),
    }),
    price: new FormControl(12, undefined, undefined, 0),
  })
]);

// 'Cheesecake', has type string
const sweets = dinnerOptions.get('0.food.dessert')!.value;

// Set the first choice to have Gnocchi as an entree
dinnerOptions.controls[0].controls.food.patchValue({entree: 'Gnocchi'});

FormBuilder

const b = new FormBuilder();
const a = b.array([
  // A raw value
  'one',
  // A ControlConfig tuple
  ['two', someSyncValidator, someAsyncValidator],
  // A boxed FormState
  {value: 'three', disabled: false},
  // A control
  b.control('four'),
]);

// ['one', 'two', 'three', 'four']
const counting = a.value;
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
Projects
None yet
Linked issues

Successfully merging this pull request may close these issues.

None yet

1 participant