'var' and 'let' in Typescript 1.5

2019-04-19 00:12发布

What exactly is the difference between using either 'var' or 'let' in Typescript? I know that 'let' allows the variable to be defined further into a scope without it being used outside of said scope. That is obviously a nice advantage for iterators in for loops. I know this is an ES6 definition, so compiling to ES6 should look nearly identical in terms of 'var' and 'let'.

But, when it compiles down into ES5 javascript which doesn't support 'let', what exactly is happening? Are there oddly named variables that the compiler creates so that it prevents using said variables in the context of the Typescript file? What happens in situations where you define many 'let' variables throughout a function? Is there a performance impact I should be concerned about?

Basically, what is happening when typescript compiles let variables to ES5 javascript?

1条回答
混吃等死
2楼-- · 2019-04-19 00:53

The easiest way to find answers to these type of questions to try it out in the TypeScript Playground.

TypeScript renames the variables within the block scope. There's no performance overhead compared to using regular variables defined with var.

This code:

var i = 0;
for (let i = 0; i < 5; i++) {}
i++;

Compiles to:

var i = 0;
for (var i_1 = 0; i_1 < 5; i_1++) { }
i++;

Here is some more information regarding let.

查看更多
登录 后发表回答