2

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?

2 Answers 2

2

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]);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Also, according to generic coding rules, it is not a good idea to have plural names of types
"Please take a look at playground" - why? What's there? What does the linked playground code demonstrate? Please state that in your answer.
Just remove = from interface definition:
What's the alternative to have plural name of this type?
For example, FieldValueMap.It mostly about distance between plural and singular form. I mean FieldValue vs FieldValues and FieldValue vs FieldValueMap
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.