I'm having compile error while reactive validation in angular 2 which is giving
error TS7017: Index signature of object type implicitly has an 'any' type
For
this.comErrors[field] = '';
const messages = this.validationMessages[field];
this.comErrors[field] += messages[key] + ' ';
it is running as it should be but when im trying to run npm run build.prod, error occurs and doesnot build my project
here is my code:
 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.'
    }
}
                That's because the compiler infers the type for validationMessages, and this type is not indexable.
The compiler needs to cast this.validationMessages to any but you are (probably) using the --noImplicitAny flag which causes the error.
You can do this:
const messages = (this.validationMessages as any)[field];
Or you can turn it into an indexable type:
type ValidationMessage = {
    required: string;
    minlength?: string;
    maxlength?: string;
}
type ValidationMessages = {
    [name: string]: ValidationMessage;
}
class A {
    validationMessages: ValidationMessages = {
        ...
    }
    ...
}
                        To declare an object where you have no idea what the values will be, but you know that the keys will be of type string:
const myObject: {[key: string]: any} = {}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With