1

In the following code, I would expect val to be detected as MyType in typescript. However, it is being detected as string which is the type of the key. Why?

type MyType = { one: string, two: string};

let sums: { [key: string]: MyType; } = {};


Object.values(sums).forEach(val => { 
console.log(value.one) // val is of type MyType 
});

for (const val in Object.values(sums)) {
     console.log(val). // why is val a string and not MyType?
}

obaqueiro
  • 982
  • 12
  • 29
  • I found out that using for ... of gives the expected result, but I still want to know why? – obaqueiro Jun 08 '21 at 22:39
  • 1
    [for ... in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops over the keys of an object. Object keys are always string (or symbols, but for in doesn't visit symbols). Object.values returns an array, so the keys of that array will be "0", "1", "2", etc. – Nicholas Tower Jun 08 '21 at 22:42
  • This may be helpful https://stackoverflow.com/questions/29285897/what-is-the-difference-between-for-in-and-for-of-statements – Alex Wayne Jun 08 '21 at 23:08

0 Answers0