javascript – 错误TS7017:对象类型的索引签名隐式地在表单验证角度2中具有“任何”类型

前端之家收集整理的这篇文章主要介绍了javascript – 错误TS7017:对象类型的索引签名隐式地在表单验证角度2中具有“任何”类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编译错误,同时在角度2中进行反应验证

error TS7017: Index signature of object type implicitly has an ‘any’
type

对于

this.comErrors[field] = '';
const messages = this.validationMessages[field];
this.comErrors[field] += messages[key] + ' ';

它正在运行,但是当我试图运行npm运行build.prod时,会发生错误并且不会构建我的项目

这是我的代码

onValueChanged(data ?: any): void {

   if (!this.companyAddForm) { return; }
    const form = this.companyAddForm;
    for (const field in this.comErrors) {
      // clear prevIoUs error message (if any)
       //errors occurs
      this.comErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.comErrors[field] += messages[key] + ' ';
        }
      }
    }
}
comErrors = {
    code: "",name: "",address: "",subscribedOn: "",contactPerson: "",contactPhone: ""
}
validationMessages = {
  'code': {
        'required': 'Company Code is required.','minlength': 'Company Code must be at least 5 characters long.','maxlength': 'Company Code cannot be more than 10 characters long.'
    },'name': {
        'required': 'Company Name is required.','minlength': 'Company Name must be at least 5 characters long.','maxlength': 'Company Name cannot be more than 25 characters long.'
    },'address': {
        'required': 'Company Address is required.','minlength': 'Company Address must be at least 5 characters long.','maxlength': 'Company Address cannot be more than 25 characters long.'
    },'subscribedOn': {
        'required': 'subscribe date is required.'
    },'contactPerson': {
        'required': 'Mobile Number is required.'
    },'contactPhone': {
        'required': 'Mobile Number is required.'
    }
}

解决方法

那是因为编译器推断出validationMessages的类型,而这种类型不是 indexable.
编译器需要将this.validationMessages转换为任何,但您(可能)使用–noImplicitAny标志导致错误.

你可以这样做:

const messages = (this.validationMessages as any)[field];

或者您可以将其转换为可索引类型:

type ValidationMessage = {
    required: string;
    minlength?: string;
    maxlength?: string;
}

type ValidationMessages = {
    [name: string]: ValidationMessage;
}

class A {
    validationMessages: ValidationMessages = {
        ...
    }

    ...
}
原文链接:https://www.f2er.com/js/155162.html

猜你在找的JavaScript相关文章