为什么打字稿转译器不能提升变量? [英] Why does the typescript transpiler not hoist variables?

查看:80
本文介绍了为什么打字稿转译器不能提升变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道ES6和TypeScript都支持块级作用域,但是在定位ES3和ES5时,输出应该是功能级作用域.我认为在TypeScript不提升变量的背后必须要有逻辑.而且我也没有遇到问题,我只是好奇为什么它没有提升变量.

I understand that ES6 and TypeScript both support block level scoping, but when targeting ES3 and ES5 the output should be function level scoping. 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.

例如,给定以下TypeScript:

For example, given the following TypeScript:

function seed(length: number, multiplier: number): number[] {
  let result: number[] = [];

  for(let i: number = 0; i < length; i++) {
    let n: number = i * multiplier;

    result.push(n);
  }

  return result;
}

转译器输出:

function seed(length, multiplier) {
  var result = [];
  for (var i = 0; i < length; i++) {
    var n = i * multiplier;
    result.push(n);
  }
  return result;
}

我期望的结果是将变量声明悬挂在函数顶部的结果.看起来像这样:

The result I would have expected would be one with the variable declarations hoisted to the top of the function. Looking something like this:

function seed(length, multiplier) {
  var
    i, n,
    result = [];

  for (i = 0; i < length; i++) {
    n = i * multiplier;
    result.push(n);
  }
  return result;
}

任何见解都将不胜感激.谢谢!

Any insight is greatly appreciated. Thanks!

推荐答案

这是因为编译器未根据编码标准输出代码.它尝试尽可能接近原始输入.

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.

请注意,无论如何,var变量都被挂在幕后(无功吊装).在这种情况下,TypeScript编译器无需更改输入,这样做会不必要地增加其复杂性.

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.

这篇关于为什么打字稿转译器不能提升变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆