Sub topic 9
Strictly Typed Forms and Non-Nullable Controls
This chapter assumes you can already create FormControl and FormGroup instances, bind them with formGroup and formControlName, and call setValue, patchValue, and reset. You also need TypeScript generics and union types.
Since Angular 14, reactive forms are strictly typed by default. Every control has a value type. The compiler checks every read and every write against it. This chapter covers how that type is inferred, why null keeps showing up in it, and how to get exact types for controls and groups.
How a Control's Type Is Inferred
FormControl<TValue> takes a generic parameter for its value type. If you leave it out, Angular infers the type from the initial value.
import { FormControl } from '@angular/forms';
const name = new FormControl('Ada');
// name: FormControl<string | null>
name.setValue('Grace'); // OK
name.setValue(null); // OK, null is part of the type
// name.setValue(42); // Compile error: number is not assignable to string | nullThe | null part surprises most people. It comes from reset(). A plain control resets to null by default, so its value type has to include null.
const city = new FormControl('Paris');
city.reset();
console.log(city.value); // nullRemoving null with nonNullable
If you pass nonNullable: true, the control remembers its initial value and reset() restores that value instead of null. The type narrows to match.
import { FormControl } from '@angular/forms';
const city = new FormControl('Paris', { nonNullable: true });
// city: FormControl<string>
city.setValue('Rome');
city.reset();
console.log(city.value); // 'Paris'
// city.setValue(null); // Compile errorDeclaring the Type Explicitly
Inference breaks down when the initial value doesn't describe the full set of allowed values. A control that starts as null but later holds a Date is the common case. Pass the generic yourself:
import { FormControl } from '@angular/forms';
type Plan = 'free' | 'pro' | 'team';
const birthday = new FormControl<Date | null>(null);
const plan = new FormControl<Plan>('free', { nonNullable: true });
// plan.setValue('enterprise'); // Compile error: not a Plan
birthday.setValue(new Date(1990, 0, 1)); // OKWithout the generic, new FormControl('free', { nonNullable: true }) infers string. The control would then accept any string.
Typing a FormGroup
A FormGroup takes its type from the controls it contains. The generic parameter describes the controls themselves, not the values. When you need the type elsewhere, for a class property declared before assignment or for a function parameter, write an interface of controls:
import { FormControl, FormGroup, Validators } from '@angular/forms';
interface ProfileForm {
name: FormControl<string>;
email: FormControl<string>;
age: FormControl<number | null>;
}
export function createProfileForm(): FormGroup<ProfileForm> {
return new FormGroup<ProfileForm>({
name: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
email: new FormControl('', { nonNullable: true, validators: [Validators.email] }),
age: new FormControl<number | null>(null),
});
}
const form = createProfileForm();
form.controls.name.setValue('Ada'); // controls are typed per key
form.patchValue({ age: 36 }); // patchValue accepts a partial object
// form.setValue({ name: 'Ada' }); // Compile error: setValue needs every keyform.controls.name has the type FormControl<string>, so editors autocomplete keys and catch typos. form.get('name') is also typed, but it returns AbstractControl<string> | null, so you have to handle null. When the key is known, controls is the better choice.
value Is Partial, getRawValue Is Not
This is the gotcha that hits most often. For the form above:
| Expression | Type | Column |
|---|---|---|
| `form.value` | `Partial<{ name: string; email: string; age: number \ | null }>` |
| `form.getRawValue()` | `{ name: string; email: string; age: number \ | null }` |
form.value leaves out disabled controls. Any control could be disabled at runtime, so the compiler marks every key as optional. Even with nonNullable everywhere, form.value.name has the type string | undefined.
import { FormControl, FormGroup } from '@angular/forms';
const form = new FormGroup({
name: new FormControl('Ada', { nonNullable: true }),
email: new FormControl('[email protected]', { nonNullable: true }),
});
form.controls.email.disable();
console.log(form.value); // { name: 'Ada' }
console.log(form.getRawValue()); // { name: 'Ada', email: '[email protected]' }
function save(data: { name: string; email: string }): void {
console.log('saving', data);
}
// save(form.value); // Compile error: properties may be undefined
save(form.getRawValue()); // OKOptional Keys and Structural Changes
Typing also limits how you change a group's shape. On a typed FormGroup, removeControl works only for keys declared optional in the controls interface. addControl and setControl accept only keys and control types that match that interface.
import { FormControl, FormGroup } from '@angular/forms';
interface ContactForm {
email: FormControl<string>;
phone?: FormControl<string>;
}
const contact = new FormGroup<ContactForm>({
email: new FormControl('', { nonNullable: true }),
});
contact.addControl('phone', new FormControl('', { nonNullable: true })); // OK, optional key
contact.removeControl('phone'); // OK
// contact.removeControl('email'); // Compile error: email is requiredWhen the keys aren't known until runtime, FormRecord is the right tool. The chapter on dynamic forms covers it.
Migrating Older Code
Projects upgraded with ng update from Angular 13 or earlier get untyped aliases: UntypedFormControl, UntypedFormGroup, UntypedFormArray, and UntypedFormBuilder. These behave the old way, with values typed as any. Migrate one form at a time:
- Replace
UntypedFormGroupwithFormGroupand the untyped controls inside it withFormControl. - Add
nonNullable: truewherever code assumes the value is nevernull. - Fix the compile errors that appear. Each one is a place where the old code could have hit
null,undefined, or a wrong type at runtime.
Common Errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `Type 'string \ | null' is not assignable to type 'string'` | The control is nullable by default | Add `nonNullable: true` or handle `null` |
| `Object is possibly 'undefined'` on `form.value.x` | `value` is `Partial` because of disabled controls | Use `getRawValue()` | |
| A control accepts any string where you wanted a union | Inferred from a literal, which widens to `string` | Pass the generic, e.g. `FormControl<Plan>` | |
| `FormControl<null>` or an unhelpful type | Initial value is `null` with no generic | Write `new FormControl<Date \ | null>(null)` |
Exercise
A control is created with new FormControl(0). After the user types 5, the code calls reset(). What is the value, and what is the control's type? How would you make reset return 0 and drop null from the type?
Show answer
The value is null and the type is FormControl<number | null>. Create it with new FormControl(0, { nonNullable: true }). The type becomes FormControl<number>, and reset() restores 0.
Exercise
Every control in a FormGroup uses nonNullable: true, yet passing form.value to a function that expects { name: string; email: string } fails to compile. Why, and what should you pass instead?
Show answer
form.value leaves out disabled controls, so its type is Partial and each property may be undefined. Pass form.getRawValue(), which always includes every control and has the full, non-optional type.
Exercise
Write a typed control for a subscription tier that allows only 'monthly' or 'yearly', starts as 'monthly', and rejects null.
Show answer
type Tier = 'monthly' | 'yearly'; const tier = new FormControl<Tier>('monthly', { nonNullable: true });. Without the explicit generic, the type would widen to string.