【问题标题】:No index signature with a parameter of type 'string' was found on type '{ [key: string]: AbstractControl; }在类型 '{ [key: string]: AbstractControl; 上找不到具有类型参数的索引签名。 }
【发布时间】:2021-06-27 12:18:49
【问题描述】:

我目前正在开发一个 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[]'.

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

问候,

【问题讨论】:

    标签: javascript angular typescript angular-reactive-forms customvalidator


    【解决方案1】:
    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}
    }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    尝试将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 }
        }
    
    

    【讨论】:

    • 它给了我这个错误 TypeError: undefined is not an object (evalating 'controls[matchTo]')
    • 如果没有工作重现,我无法真正测试这一点,但也可以尝试编辑后的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2021-12-04
    • 2021-10-16
    相关资源
    最近更新 更多