adplus-dvertising

Index signature of type 'string' on interface not recognized (typescript)

Asked 2 years ago
Viewed 87 times

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?

asked 2 years ago

Correct Answer

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]);
}
answered 2 years ago

Other Answer

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.

answered 2 years ago