[英]No index signature with a parameter of type 'string' was found on type '{ [key: string]: AbstractControl; }
I'm currently working on an Angular project and defining a custom validator for a reactive form, and I'm having this error within the custom validators function, which being built.我目前正在开发一个 Angular 项目并为响应式表单定义一个自定义验证器,并且我在正在构建的自定义验证器 function 中遇到此错误。 Below are the code and the error received.下面是代码和收到的错误。
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 }
}
}
The Error Message:错误信息:
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[]'.
Can someone explain why this happens and how to handle it the correct way?有人可以解释为什么会发生这种情况以及如何以正确的方式处理它吗?
Regards,问候,
Try casting control?.parent?.controls
to { [key: string]: AbstractControl;尝试将control?.parent?.controls
为 { [key: string]: AbstractControl; } since it has two possible types. } 因为它有两种可能的类型。 If it's type is AbstractControl[]
, then the index is not of type string, but of type number.如果它的类型是AbstractControl[]
,那么索引不是字符串类型,而是数字类型。
Something like this像这样的东西
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 }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.