I have a formgroup that looks like this:
this.formBuilder.group<{
id: number;
nameDe?: FormControl<string>;
nameFr?: FormControl<string>;
nameIt?: FormControl<string>;
}>({
id: value?.id || null
});
The main focus is on the "nameXY" fields. These fields are dynamically added based on certain conditions.
languages.forEach((lang) => { // languages could be ['De', 'Fr'] or ['Fr', 'It']
const nameIdentifier = 'name' + lang;
formGroup.addControl(nameIdentifier, new FormControl<string>(value?.[nameIdentifier] || '', Validators.required));
});
However, I am encountering an error:
Argument of type 'string' is not assignable to parameter of type ...
This issue arises because nameIdentifier
is considered as just a string and not specifically 'nameDe' | 'nameFr'| 'nameIt'.
I initially attempted to define the type for nameIdentifier
explicitly:
const nameIdentifier: 'nameDe' | 'nameFr' | 'nameIt' = 'name' + lang;
But then, I encountered this error:
Type 'string' is not assignable to type '"nameDe" | "nameFr" | "nameIt"'.ts(2322)
At this point, I am running out of ideas. :) Is there a cleaner solution without resorting to excessive explicit typing?