Let's say I have multiple variables like this:
formGroup: FormGroup;
input = [
{'key': value},
{'key': value}
]
output = [
{'key': value},
{'key': value}
]
I also have input
and output
as options in a form field dropdown
which gives the user the ability to change their value with just a click of a button.
When the user submits the form, the onClick funtion
takes the form values and updates the fields. To do this, I did something like this
onSubmit(): void {
this[this.formGroup.controls['controlName'].value].push(...)
}
constructor(formBuilder: FormBuilder){
this.formGroup = formBuilder.group({
controlName:''});
}
this.formGroup.controls['controlName'].value
would have the value as input
or output
.
However, this results in an error
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type
Casting the value or indexing doesn't seem to solve the issue. Is there no way to get around this error, or the only option I have is to use if/ switch statements.
CodePudding user response:
Do the following:
//somewhere in your project
export type MyType = 'input' | 'output';
@Component({...})
export class YourComponent {
input = [...];
output = [...];
onSubmit(): void {
const dropdownValue = this.formGroup.get('controlName')?.value; // it can be undefined
const index: MyType = dropdownValue ? dropdownValue as MyType : 'input';
this[index].push(...);
}
}
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type
Typescript complaints that the value you are getting is of type any
and probably while trying to use it as an index, is wrong, for this, is recommended to use strong typing, such as creating a type
where will match in this case with either of your class properties