FormControl / FormGroup / FormArray value type
Asked Answered
D

2

7

I want my FormControl (FormGroup / FormArray) be strongly typed so when I have e.g.

interface SomeSource {
  id: string;
  name: string;
}

and I transformed it to e.g.

let form = new FormGroup<SomeSource>({
  id: new FormControl('test id'),
  name1: new FormControl('test name')
});

TypeScript had thrown an error: the name is not found on FormGroup.

Also in the ideal world the form.value should be of SomeSource type (and not any).

Problem is that there is no way to specify this generic type for any AbstractFormControl child.

I think this is fairly easy to override FormGroup with an own interface. However, is there a way to achieve this just using Angular? If no, are there third party solutions?

Motivation: I want to easily refactor my SomeSource. Currently when I refactor SomeSource interface, the form is not adapted and no error is thrown => there is a room for some bugs.

Davis answered 24/1, 2017 at 14:36 Comment(4)
well you are using name1 in your formgroup?Marguritemargy
yes, because I want an error when I have a typo or I refactor my SomeSource. This is just a typo simulationDavis
I don't think the Angular form classes provide this functionality, but I think you should be able to create your own TS class and leverage generics to achieve this behavior. Reply back if you need an example.Myel
@Myel thanks, I think I can handle it. I just want to avoid reinventing the wheel...Davis
C
2

Since v14, Angular implemented native typings for the Form module: https://angular.io/guide/typed-forms

Cadmus answered 2/8, 2022 at 18:26 Comment(0)
C
4

UPDATE: Angular v14 finally added typed forms, see the official docs.


OLD ANSWER:

There is an elegant solution for your problem - leverage TypeScript declaration files (*.d.ts) to introduce generic interfaces extending the standard form classes like AbstractControl, FormControl, etc. It doesn’t introduce any new functionality and has no footprint in the compiled JavaScript, but at the same time enforcing strong type checking.

It was suggested by Daniele Morosinotto in March this year and there are talks now to include it in Angular 9.

Adopting the solution is straightforward:

  1. Download TypedForms.d.ts from this gist and save it as src/typings.d.ts in your project (Angular 6+ already knows how to use this file).
  2. Start using the new types (FormGroupTyped<T>, FormControlTyped<T>, etc.) whenever you need a strong type validation (see examples in that gist or stackblitz).

For more information, check out a blog post analysing available solutions for strongly typed forms.

Cowley answered 6/6, 2019 at 11:17 Comment(0)
C
2

Since v14, Angular implemented native typings for the Form module: https://angular.io/guide/typed-forms

Cadmus answered 2/8, 2022 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.