首页 > 解决方案 > 当我在我的 Angular 应用程序中进行验证时,我面临在“AbstractControl[] 错误类型上找不到带有“字符串”类型参数的索引签名

问题描述

当我在我的角度应用程序中进行验证时,我遇到了这个错误:

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

这是错误来自的方法:

matchValues(matchTo: string): ValidatorFn {

   return (control: AbstractControl) => {

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

}

我刚刚开始使用 angular 和 TypeScript,但我不知道如何解决它。任何帮助,将不胜感激。

标签: javascriptangulartypescript

解决方案


您必须定义对象具有哪种索引类型。在您的情况下,它是基于字符串的索引。

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

推荐阅读