- 
                Notifications
    You must be signed in to change notification settings 
- Fork 13.1k
Closed
Labels
CommittedThe team has roadmapped this issueThe team has roadmapped this issueEffort: DifficultGood luck.Good luck.FixedA PR has been merged for this issueA PR has been merged for this issueSuggestionAn idea for TypeScriptAn idea for TypeScript
Milestone
Description
Hi,
I was recently surprised to see that TypeScript 1.5 (using ntypescript, so recent master) doesn't support transpiling down to ES5 the separate scope functionality of ES6 when using a for loop with a let-initialized iterator.
For example:
function buttonsWithLet(count, targetElement) {
  for (let i = 1; i <= count; i+= 1) {  //error 4091:  Loop_contains_block_scoped_variable_0_referenced_by_a_function_in_the_loop_This_is_only_supported_in_ECMAScript_6_or_higher
    var button = makeButton("alert " + i);
    button.onclick = function() {
      alert("This is button " + i + ".");
    };
    targetElement.appendChild(button);
  }
}This is where Error 4091 was implemented.
5f2588f
3b3a94c
Is the TypeScript team open to transpiling this code in ES5 mode? If so, would you accept a pull request? The above code is transpiled by Babel as such which is really clean:
function buttonsWithLet(count, targetElement) {
    var _loop = function (i) {
        button = makeButton("alert " + i);
        button.onclick = function () {
            alert("This is button " + i + ".");
        };
        targetElement.appendChild(button);
    };
    for (var i = 1; i <= count; i += 1) {
        var button;
        _loop(i);
    }
}but a plausibly easier transpile might be:
function buttonsWithVarAndIIFE(count, targetElement) {
    for (var i = 1; i <= count; i += 1) {
        var button = makeButton("alert " + i);
        button.onclick = (function (i) {
            return function () {
                alert("This is button " + i + ".");
            };
        })(i);
        targetElement.appendChild(button);
    }
}Metadata
Metadata
Assignees
Labels
CommittedThe team has roadmapped this issueThe team has roadmapped this issueEffort: DifficultGood luck.Good luck.FixedA PR has been merged for this issueA PR has been merged for this issueSuggestionAn idea for TypeScriptAn idea for TypeScript