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

Bib*_*kya 15 javascript typescript angular

我正在编译错误,同时在角度2中进行反应验证

错误TS7017:对象类型的索引签名隐式具有"任何"类型

对于

this.comErrors[field] = '';
const messages = this.validationMessages[field];
this.comErrors[field] += messages[key] + ' ';
Run Code Online (Sandbox Code Playgroud)

它正在运行,但是当我试图运行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.'
    }
}
Run Code Online (Sandbox Code Playgroud)

Nit*_*mer 26

那是因为编译器推断出类型validationMessages,而且这种类型不可索引.
编译器需要强制this.validationMessages转换,any但您(可能)使用--noImplicitAny导致错误的标志.

你可以这样做:

const messages = (this.validationMessages as any)[field];
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

    ...
}
Run Code Online (Sandbox Code Playgroud)


tho*_*max 5

在不知道值是什么的情况下声明一个对象,但是您知道键的类型为字符串:

const myObject: {[key: string]: any} = {}
Run Code Online (Sandbox Code Playgroud)