error TS7017: Index signature of object type implicitly has an 'any' type in form validation angular 2
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} = {}
Using Object Destructuring you can fix with:
const {[field]:messages} = this.validationMessages;