1

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?

1
  • What is your use case? Commented Dec 1, 2017 at 7:41

1 Answer 1

3

You know that for k in o loops over o's property keys, not its values, right? Additionally, JavaScript only really allows strings as property keys, and will silently coerce non-strings to strings:

From MDN's documentation for accessing properties:

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

So that means that TypeScript is actually correct when it types obj as string:

for (let obj in myObj) {
    console.log(typeof obj); // "string"
    if (obj === "1") // okay now {
      myObj[obj] = 123; // okay, property value is a number
    }
}

Hope that helps; good luck!

Sign up to request clarification or add additional context in comments.

2 Comments

So if I wanted to use the key as a number, I'd be required to use something like parseInt or parseFloat?
Yes, something like that (e.g., Number(obj) or +obj)

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.