I can not respond in an authoritative way in specific, but from what I know of compilation and transpilation , it makes some sense because the extra control that let
gives is the scope, which the TypeScript compiler has already ensured is appropriate, so you do not have to send something to JS for it to check again. Once it knows it is in the right scope, when JavaScript code is generated there is no reason for the JS compiler to take care of this. It would be a redundant compilation job. I imagine compiling var
in JS is faster than compiling let
.
The JS code generated by TS does not have to be robust, it does not have to be readable, it's not for humans, it needs to be efficient and well-made to work properly, it's another level of abstraction.
In fact it can be seen that it protects the variable by changing its name where it has let
:
function foo() {
var x = 1;
var y = 3;
if (true) {
var x = 2;
var y_1 = 4;
console.log(x);
console.log(y_1);
}
console.log(x);
console.log(y);
}
See running and transpiling on TypeScript Playground . I also put it in GitHub for future reference .
Additionally using var
ensures that it runs on older browsers that do not have let
.