In TypeScript, I'm attempting to use a for (let x in obj) loop but the TypeScript compiler does not recognise the type of x correctly... it always assumes it is of type string.
In the example below, the type of obj outside the for loop is detected correctly. The TypeScript compiler recognizes it as a number. However, the obj inside the for loop is recognized as a string when it should be a number.
let myObj: { [key: number]: number } = { 0: 43, 5: 23 };
let obj = myObj[0]; // let obj: number
for (let obj in myObj) {
if (obj == 1) {
// ^ [ts] Operator '==' cannot be applied to types 'string' and 'number'.
// TypeScript compiler thinks 'obj' is of type 'string' when used in `for in` loop.
}
}
This casues errors in my code and I'm not sure how to work around this issue. Is it something I'm doing wrong, or is it a TypeScript bug?