Angular Reactive Form Control Implicit Type Inference and Reset Semantics

Scenario

We would like IDE error linting in case we try to set an incorrect type value on a form control. This is a feature of the latest version of Angular.

We also want controls to reset to their constructor assigned initialization values .

Approach

Initialize the control with a string value.

const c = new FormControl('');

Set the value of the control to a non string value.

c.setValue(2);

Angular now lints the code with the following error message.

Error in src/app/app.component.ts (16:16)Argument of type 'number' is not assignable to parameter of type 'string'.

Note that we could have applied the type of the control generically like this.

const c = new FormControl<string>('');

If we call reset on c .

c.reset();

The value of c is set to null. That’s because the type of c has been inferred to <string | null>. If we don’t want this we can turn off nullability.

const d = new FormControl('start', { nonNullable: true });

If we d.reset() the value assigned to d will be the string start .

Demo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation