当我在我的Angular应用程序中进行验证时,我面临Noindexsignaturewithaparameterofa'string'wasfoundontype'AbstractControl[]错误
当我在我的 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 };
}
}
- You got the undefined error as you are not check the parent && parent.controls exists or not, since the Validation fn will be extecuted many times as Angular way. I just create a demo for your reference https://stackblitz.com/edit/angular-ivy-t6kmze?file=src/app/app.component.ts
THE END
二维码