Why does the typescript transpiler not hoist variables?

六月ゝ 毕业季﹏ 提交于 2019-12-06 09:44:00

It's because the compiler doesn't output code based on a coding standard. It tries to be as close as possible to the original input.

Note that var variables are hoisted behind the scenes anyway (var hoisting). There's not a need for the TypeScript compiler to change the input in this case and doing so would needlessly increase its complexity.

I think there has to be a logic behind why TypeScript isn't hoisting variables.. and I'm not running into a problem, I'm more just curious why it doesn't hoist variables.

Exactly that. Because it isn't a problem, why go though the effort of hoisting?

Also in case of let It would actually be wrong to hoist it the way you showed.

Temporal Dead Zone

Firstly let variables cannot be used before declaration like var variables could be. With var you would get undefined. With let you would get a ReferenceError due to temporal deadzone. Fortunately TypeScript will give you a compile time error anyways so you don't run into that at runtime :

console.log(a); // Error: Block scoped variable used before declaration 
let a = 123;

Block Scoping

let variables declared in a for are only available in the for loop. This is because they are block scoped and not function scoped. More on this

Again TypeScript will give you a compile time error if you misuse let (instead of you running into it at runtime):

for(let i: number = 0; i < 10; i++) {    
}  
console.log(i); // Error: no variable i in scope

Hope that helps 🌹

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!