'let and 'var' are the same in Typescript?

Edie Johnny picture Edie Johnny · May 25, 2016 · Viewed 9.4k times · Source

I was taking a look at AngularJS 2 and Typescript and I decided to make something with this just to learn the basics of Typescript. With many research I found good topics about modules, Typescript, and one of them was talking about the 'let' and 'var' command to declare variables; according to this question, the Typescript code below should display only one alert and throw an error in the console:

test.ts:

for(let i = 0; i < 1; i++) {
    alert(i);
}
alert(i);

Compiled test.js:

for(var i = 0; i < 1; i++) {
    alert(i);
}
alert(i);
//# sourceMappingURL=test.js.map

But it isn't. The compiler "ignores" the "let" command and turns it into the "var" command. Why does this happen? Does Typescript only works properly with classes?

I'm using AngularJS configuration for 'npm start', so it compiles my 'test.ts' file automatically:

  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },

Answer

David Sherret picture David Sherret · May 25, 2016

But it isn't. The compiler "ignores" the "let" command and turns it into the "var" command. Why does this happen? Does Typescript only works properly with classes?

The compiler by default transpiles to ES3. The let keyword doesn't exist in ES3 and so the emitter must emit code using syntax available in ES3... in this case the best replacement for the let keyword is the var keyword.

If you want it to emit with the let keyword, then you must target ES6—"target": "es6" in tsconfig.json or the command line option --target es6. Doing this will output with the same code that you inputted.

Note that even though your code works at runtime, it throws an error to let you know you have made a mistake at compile time:

for(let i = 0; i < 1; i++) {
    alert(i);
}
alert(i); // compile error: cannot find name 'i'