- 2 minutes read

Angular 14 ships with typed reactive forms, and it's just great. Type inference, backward compatibility, fine-tuning options, and user-defined type definitions - it's all there. It's been a long wait, but it was worth it!

Type inference and backward compatibility

Truth to tell, I noticed the feature when I ran into strange bugs after updating to Angular 14. As it turns out, Angular determines the type of the form controls by their default values:

const name = new FormControl(''); // --> string | null const truth = new FormControl(true); // --> boolean | null

Awesome! However, after updating to Angular 14, you'll probably have to fix zillions of type errors. In the meantime, you can use UntypedFormControl instead of FormControl.

Fine-tuning

The inferred type string | null puzzled me at first. You can get rid of it by adding an option:

const name = new FormControl('', { nonNullable: true }); // --> string

This guarantees the form control is never null. The null value is confusing because form controls reflect the user input, and users never can input null values. Even if they don't input anything, it's still an empty string. However, as Netanal Basal explains, FormControl.reset() sets the value to null unless you add the nonNullable attribute.

User-defined typings

FormControl has become a generic type. So you can override the default by passing a type parameter:

const salary = new FormControl(); // --> number | null

This also works for entire FormGroups, as Netanal Basal reports::

// please read Netanals blog for an // explanation of this type magic :) export type ControlsOf> = { [K in keyof T]: T[K] extends Record ? FormGroup> : FormControl; }; interface Employee { name: string; salary: number; } const employeeForm = new FormGroup>({ name: new FormControl(), salary: new FormControl() })

Wrapping it up

In a nutshell, Angular 14 finally ships with simple and valuable typed reactive forms. You'll love it!

This article is merely a litte teaser. Please read the full story at Netanal Basal's blog.


Comments