Angular introduced Model-driven forms with its FormBuilder class, whose primary method group
has a signature like this:
group(controlsConfig: {
[key: string]: any;
}): FormGroup;
The any
is actually an array with the format:
[
initial value of model's property,
sync validator(s),
async validator(s)
]
Where only the first element is required.
I decide I'd like something a little more strongly typed than that, particularly on anything which is associated with a strongly typed Model, so I re-define the function in terms of T:
declare interface FormBuilder2 extends FormBuilder {
group<T>(controlsConfig: {
[K in keyof T]?: [T[K], ValidatorFn | ValidatorFn[] | null, ValidatorFn | ValidatorFn[] | null];
}): FormGroup;
}
This also means that all my formControlNames in the HTML (and of course here in the group() call) must match the model's properties, which I prefer.
It seems to work but for one snafu:
this.optionsForm = this.formBuilder2.group<CustomerModel>({
status: [this.model.status, [Validators.required], null],
lastOrder: [this.model.lastOrder, null, null],
comments: [this.model.comments, null, null],
});
I must provide null
on the unused array slots.
Is there a way to get Typescript to omit the need for the extraneous null
s?