typescriptfor-in-loopobject-property

Typescript element implicitly has type any with for...in loops


I have a JSON object imported from a JSON file (with resolveJsonModule: true). The object looks like this:

"myobject": {
  "prop1": "foo",
  "prop2": "bar"
}

and it's type therefore looks like this:

myobject: { prop1: string, prop2: string }

That's very nice but when I try to use a for...in loop,

for (const key in myobject)  {
  console.log(myobject[key])
}

I get this error:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ "prop1": string; "prop2": string; }'.
  No index signature with a parameter of type 'string' was found on type '{ "prop1": string; "prop2": string; }'.

I understand that this means the iterator key is of type string and not of type 'prop1' | 'prop2'. But I don't understand why the iterator doesn't get this type because I'm explicitly iterating through the property names of myobject. Did I miss a tsconfig property that enables this behavior? I would like not to do this:

for (const key in myobject)  {
  console.log(myobject[key as 'prop1' | 'prop2'])
}

Because:

  1. I might add new properties in the future; and
  2. this seems a bit cheaty, and I feel like there is a better way to do that.

Solution

  • A better way to this is:

    for (const key in myobject)  {
      console.log(myobject[key as keyof typeof myobject])
    }
    

    In this way, it won't break when you add a property or rename it