When I'm validating in my angular app I'm facing No index signature with a parameter of type 'string' was found on type 'AbstractControl[] Error

Viewed 802

When I'm validating in my angular app I'm facing this error:

src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AbstractControl[] | { [key: string]: AbstractControl; }'.
  No index signature with a parameter of type 'string' was found on type 'AbstractControl[] | { [key: string]: AbstractControl; }'.

45             return control?.value === control?.parent?.controls[matchTo].value ? null : {isMatching: true}
                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is the method the error is coming from:

matchValues(matchTo: string): ValidatorFn {

   return (control: AbstractControl) => {

        return control?.value === control?.parent?.controls[matchTo].value ? null : {isMatching: true}
       }
    

}

I'm just starting angular and TypeScript and I don't know how to fix it. Any help would be appreciated.

3 Answers

You have to define what kind of index type the object has. In your case it is a string based index.

matchValues(matchTo: string): ValidatorFn {
    return (control: AbstractControl) => {
        return control.value === (control?.parent?.controls as { [key: string]: AbstractControl })[matchTo].value ? null : { isMatching: true };
    }
}

i just ignored the line using // @ts-ignore and it is working fine.

Here the index isn't string. it is a number. then the answer is:

 matchValues(matchTo: string): ValidatorFn {
    return (control: AbstractControl) => {
      const controls = control?.parent?.controls as { [key: string]: AbstractControl; };
      let matchToControl = null;
      if (controls) matchToControl = controls[matchTo];
      return control?.value === matchToControl?.value
        ? null : { isMatching: true }
    }
  }
Related