Jarek
Jarek

Reputation: 7729

Typescript - closure inside loop

I am trying to use closures in Typescript inside a loop, but I've got some serious problems:

for(let vehicle of vehicles) {
    update(location => 
        {
            vehicle.location = location;
        }
    );
}

I am using Typescript 1.8.1 and I need to target ES5, when I compile the following error shows:

Loop contains block-scoped variable 'vehicle' 
referenced by a function in the loop. 
This is only supported in ECMAScript 6 or higher.

If i use var instead of let in the loop, it uses last value of vehicle for all closures.

Is there any good workaround for this problem when targeting ES5?

Upvotes: 0

Views: 757

Answers (3)

basarat
basarat

Reputation: 275819

Is there any good workaround for this problem when targeting ES5?

Please update to TypeScript nightly. This feature is supported there and will eventually make it to a release.

More

https://basarat.gitbooks.io/typescript/content/docs/getting-started.html#nightly-typescript

Upvotes: 2

Ruan Mendes
Ruan Mendes

Reputation: 92274

Yes, bind the function that is using the closure variable, that will create a separate vehicle reference for each of the inner functions in the loop

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

for(let vehicle of vehicles) {
    update(function(veh, location)  {
        veh.location = location;
    }.bind(null, vehicle));
}

Upvotes: 0

ArcSine
ArcSine

Reputation: 644

This is a problem because the function you calling in update is bound to the variable vehicle, not the loop iteration vehicle. You would need to do something like:

for(let vehicle of vehicles) {
    (vehicleClosure => {
        update(location => vehicleClosure.location = location)
    })(vehicle)
}

Or use a JavaScript runtime that supports scoping via let which should behave as intended.

Upvotes: 0

Related Questions