Danny Hoeve Danny Hoeve - 1 month ago 17
TypeScript Question

Index signature of object type implicitly has an 'any' type in Angular 2 official documentation

I have an error when I tried to implmement the Reactive Form validation of the Angular 'Cookbook' section, you can watch it over here: https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#reactive

I tried to google this problem but I couldn't really find a solution.

The error code is :


index signature of object type implicitly has an 'any' type


The following code is being used:

onValueChanged(data?: any) {
if (!this.form) { return; }
const form = this.form;

for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = ''; // This sends a error code
const control = form.get(field);

if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field]; // This sends a error code
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' '; // This sends a error code
}
}
}
}

formErrors = {
'imei': '',
'deviceTypeId': ''
};

validationMessages = {
'imei': {
'required': 'Imei is required.',
'minlength': 'Imei must be at least 4 characters long.',
'maxlength': 'Imei cannot be more than 24 characters long.',
},
'deviceTypeId': {
'required': 'Device Type is required.'
}
};


I wonder if I'm missing something crucial? The rest of my code is similar to the Form Validation guide.

Answer

You can fix this by specifying index signature type explicitly. For example:

formErrors:{ [key: string] : string; } = {
    ...
};

validationMessages:{ [key: string] : { [key: string] : string; } }  = {
    ...
};

If you want to ignore these errors you can just specify any as type of mentioned members (e.g formErrors:any) or use suppressImplicitAnyIndexErrors compiler option.