Reputation: 725
I have this code:
const sectionInstance: FieldValues = sectionInstances[i]
for (const field in sectionInstance) {
console.log(sectionInstance[field])
}
field
here is of course a string. Here is the type definition for FieldValues
:
export interface FieldValues = {
[key: string]: FieldValue;
}
Still I get this error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FieldValues'. No index signature with a parameter of type 'string' was found on type 'FieldValues'.Vetur(7053)
Haven't I declared an index signature of type 'string' for interface FieldValues
? Why do I get this error?
Upvotes: 2
Views: 210
Reputation: 1372
Just remove =
from interface definition.
Please take a look at playground
interface FieldValues {
[key: string]: FieldValue;
}
...
const sectionInstance: FieldValues = sectionInstances[i];
for (const field in sectionInstance) {
console.log(sectionInstance[field]);
}
Upvotes: 2
Reputation: 984
As I know, Typescript can not infer the key type from [key: string]
. it's only useful when you are trying to generalize that some keys(probably except the others) might be there with string type. TS cannot ensure that the key you are accessing in the for
is of the type string
you used in [key: string]
. you should say it explicitly.
Upvotes: 0