Skip to content

Transpile separate scope in each for loop iteration with let and ES5 #3915

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);
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CommittedThe team has roadmapped this issueEffort: DifficultGood luck.FixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions