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

问题描述

我目前正在处理一个 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 }
    }