Danny Hoeve
Danny Hoeve

Reputation: 722

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.

Upvotes: 0

Views: 835

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37938

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.

Upvotes: 2

Related Questions