2

Consider this code:

var a = [];

for (var i in a)
  /* nothing */;

var i : number;

i = 9;

If I compile this, the compiler complains about the last line, saying, "Cannot convert 'number' to 'string'".

Presumably the for..in loop created i as a string, but I would have expected the compiler to complain about var i : number rather than wait until i = 9 before it complained.

If I change var i : number to var i : number = 8, the compiler still doesn't complain until it reaches i = 9.

Is this a bug, or am I missing something?

2 Answers 2

3

If you had originally declared the variable it would warn you where you predict. For example, if you placed this line at the top of your code:

var i: string;

It would warn you of the duplicate identifier on the line:

var i: number;

It doesn't detect the duplicate identifier when you declare i in the for statement, perhaps it should - so you end up with a different error, which is when you assign a value of the wrong type.

If you want the duplicate identifier warning, which is the first and foremost error here, your best bet is to log the bug on http://typescript.codeplex.com/

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

1 Comment

Thank you, Steve. I did as you suggested: typescript.codeplex.com/workitem/771
0

It's not a bug, to understand what's going on you have to understand how JavaScript behaves, especially around the area regarding hoisting. Essentially, the code you have above is the same as:

var a = [],
    i;

for (i in a)
  /* nothing */;

i = 9;

Since i is first encountered in your for statement, its type is becoming a string. for (key: string in someVar) { }.

Here's an article that describes hoisting and scoping in JavaScript: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

4 Comments

But that doesn't explain why the compiler doesn't complain about var i : number = 8.
The compiler complains for me when I do var i: number = 8;, at least in version 0.8.2.
I'm using 0.8.3, and it doesn't complain.
Must be a new bug in 0.8.3. It complains for me in 0.8.2, but not in typescriptlang.org/Playground Wierdly, in 0.8.3 you can trace typeof(i) and it will tell you 'number', but if you then try i * 10 you get the error described by @oz1cz in the OP.

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.