This project is read-only.

Typed for in iterator variables?

Topics: Language Specification
Apr 20, 2014 at 6:41 PM

So back in the day, TypeScript used strings as for in iterator variables. This was correct as far as JavaScript goes, but I guess people complained because it was too strict.

So currently for in variables are type any. Period.

Would it be possible to add explicit types to the variable declaration in a for in loop? Example:
for (var userId: string in obj) {
That is consistent with other places you can use var where explicit types are allowed, and it would allow writing safer code.
Apr 21, 2014 at 11:06 AM
One could use foreach where string is required:
Object.keys(obj).forEach(userId => {
    userId.charAt // string
The argument in favour of not providing annotation is rather obscure. See workitem #1789.
Apr 21, 2014 at 6:05 PM
Your link brings to mind something I can do. I can do this:
var userId: string; for (userId in obj) {
The syntax looks a little weird, but at least it works. The variable userId is a string, As Brendan Intended.
May 11, 2015 at 11:02 PM
I'm teaching programming to beginning students at our university using typescript. Since they may later use other languages, I urge them to use explicit type annotations to get used to it. The exception in this loop is a very weak spot and an inconsitency, I can't explain to them. At least it should be possible to give an explicit any-annotation.