Here is a snippet of my code, where I am attempting to call a method using an indexed signature. It functions properly when the function name is manually added, but how can I call it using object notation for dynamic calls?
createFormControl(formControls:PatientFormProps[]):void {
for (const control of formControls) {
const newPatientFormControl = new FormControl();
if (control.options.required) {
const value = { label: 'email' };
newPatientFormControl.setValidators([Validators.required, PatientFormService.formProps["email"]]);//works
newPatientFormControl.setValidators([Validators.required, PatientFormService.formProps[value.label]);//error
}
this.patientForm.addControl(control.key, newPatientFormControl);
}
console.log(this.patientForm);
}
Error Message:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ email: () => { error: boolean; }; }'.
No index signature with a parameter of type 'string' was found on type '{ email: () => { error: boolean; }; }'.ts(7053)
The target method that I am trying to invoke is shown below:
export class PatientFormService {
static formProps = {
"email": () => {
console.log('email control');
return { error: true };
}
}
}
In my attempt in TypeScript Playground, I encounter a similar issue:
UPDATE:
I attempted the following modification:
createFormControl(formControls:PatientFormProps[]):void {
for (const control of formControls) {
const newPatientFormControl = new FormControl();
if (control.options.required) {
const { key } = { ...control };//fetching only necessary key
newPatientFormControl.setValidators([Validators.required, PatientFormService.formProps[key as const]]);//does not work
}
this.patientForm.addControl(control.key, newPatientFormControl);
}
console.log(this.patientForm);
}