Let's consider a scenario:
I have two forms, form1
and form2
, each containing multiple FormControls. The common property among them is the FormControl with an id
.
Now, I need to pass these forms as arguments to a method that should only require knowledge of the id
property.
How can I specify the parameter type for myMethod()
? I want to ensure that the parameter for myMethod
is a FormGroup with a FormControl named id
, along with any other optional FormControls.
I attempted using
FormGroup<{id: FormControl}>
, but it resulted in an error:
TS2345: Argument of type 'FormGroup<{ id: FormControl<any>; name: FormControl<any>; }>' is not assignable to parameter of type 'FormGroup<{ id: FormControl<any>; }>'.
Property 'name' is missing in type '{ id: FormControl<any>; }' but required in type '{ id: FormControl<any>; name: FormControl<any>; }'.
What would be the correct way to define the type for the form
with just the id
field?
export class AppComponent {
readonly form1 = new FormGroup({
id: new FormControl(),
name: new FormControl(),
});
readonly form2 = new FormGroup({
id: new FormControl(),
title: new FormControl(),
});
ngOnInit(): void {
this.myMethod(this.form1); // Throws error
this.myMethod(this.form2); // Throws error
}
myMethod(form: FormGroup<{id: FormControl}>) {
// do something
}
}