I have a typed FormGroup based on the following interface. Note that proId is optional:
interface FormData {
name: FormControl<string>;
age: FormControl<number | null>;
active: FormControl<boolean>;
proId?: FormControl<number>;
}
constructor(private formBuilder: NonNullableFormBuilder) {}
form: FormGroup<FormData> = this.formBuilder.group({
name: '', // will be initialized in ngOnInit when @Input() can be accessed
age: null as number | null, // will be initialized in ngOnInit when @Input() can be accessed
active: false as boolean,
proId: 0
});
But how to initialize the proId FormControl correctly? With my solution above I get the following error:
TS2322: Type 'FormGroup<{ name: FormControl<string>; age: FormControl<number>; active:
FormControl<boolean>; proId: FormControl<number>; }>' is not assignable to type
'FormGroup<FormData2>'. Type 'FormControl<number> | undefined' is not assignable to type
'FormControl<number>'. Type 'undefined' is not assignable to type 'FormControl<number>'.
And a second question:
Is it the correct way to initialize the following two fields like this:
age: null as number | null
active: false as boolean
Because if I only use
active: false
I get the following error:
Type 'FormControl<boolean>' is not assignable to type 'FormControl<false>'. Type 'boolean'
is not assignable to type 'false'.