javascript - 当我在我的 Angular 应用程序中进行验证时,我面临在类型'AbstractControl []错误上找不到类型为 'string' 的参数的索引签名

标签 javascript angular typescript

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

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,但我不知道如何解决它。任何帮助将不胜感激。

最佳答案

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

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

关于javascript - 当我在我的 Angular 应用程序中进行验证时,我面临在类型'AbstractControl []错误上找不到类型为 'string' 的参数的索引签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65353592/

相关文章:

angular - TypeScript 编译中缺少 Module build failed ts。请通过 'files' 或 'include' 属性确保它在您的 tsconfig 中

javascript - 基于 ajax 的网页 - 这样做的好方法?

javascript - 推特 Bootstrap : Remove/Toggle the active state of checkbox-like button group

javascript - 在 JavaScript 中设置输入值时引发的事件

angular - 用于 Angular2 Grid Web API 数据绑定(bind)的 Kendo UI

CSS 过渡动画 Jank w/zindex on Mac (Retina)

javascript - 我们可以在外部 .ts 文件中声明类中所需的所有变量吗?

typescript - 如何将具有泛型的函数类型应用于函数

c# - Angular 4 - 如何从 ASP.Net web api 获取数据

JavaScript 输入字段大写是安全的