在类型 '{ [key: string]: AbstractControl; 上找不到参数类型为 'string' 的索引签名; }

No index signature with a parameter of type 'string' was found on type '{ [key: string]: AbstractControl; }

我目前正在处理一个 Angular 项目并为反应式表单定义自定义验证器,但我在正在构建的自定义验证器函数中遇到此错误。以下是代码和收到的错误。

 initializeForm() {
    this.registerForm = new FormGroup({
      username: new FormControl('', Validators.required),
      password: new FormControl('', [Validators.required,
      Validators.minLength(4),
      Validators.maxLength(8)]),
      confirmPassword: new FormControl('', Validators.required)
    });
  }

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

错误信息:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ [key: string]: AbstractControl; } | AbstractControl[]'.
  No index signature with a parameter of type 'string' was found on type '{ [key: string]: AbstractControl; } | AbstractControl[]'.

有人可以解释为什么会发生这种情况以及如何正确处理它吗?

此致,

尝试将 control?.parent?.controls 转换为 { [key: string]: AbstractControl; } 因为它有两种可能的类型。如果它的类型是AbstractControl[],那么索引不是字符串类型,而是数字类型。

像这样


 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 }
    }

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