TS为什么在函数体内抱怨函数声明 [英] Why TS complains with function declarations inside function body

查看:135
本文介绍了TS为什么在函数体内抱怨函数声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在TS中遇到此错误:





很清楚为什么会发生错误:

  function external(){

if(true ){
function inner(){//嵌套函数声明

}
}
}

但是我的问题是-为什么TS会抱怨这一点-在转换为ES5时应该避免嵌套函数声明的某些技术原因吗?



函数表达式会是更好的选择,为什么?

解决方案

< blockquote>

将函数表达式作为更好的选择


是。以下是处理方法:

  function external(){
if(true){
const inner = function(){// OK
}
}
}




为什么?





  • ES模块处于严格模式默认。

  • 严格模式不允许在块中声明函数



原因被禁止在原始JavaScript规范中。简短版本:实施之间的行为不一致


注意已知有几种广泛使用的ECMAScript实现支持使用FunctionDeclaration作为语句。但是,在应用于此类FunctionDeclaration的语义中,实现之间存在重大且不可调和的变化。由于存在这些无法协调的差异,因此将FunctionDeclaration作为Statement的使用会导致代码无法在实现之间可靠地移植。建议ECMAScript实现禁止使用FunctionDeclaration或在遇到这种情况时发出警告。 ECMAScript的未来版本可能会定义用于在Statement上下文中声明函数的其他可移植方法。


因此,严格模式应运而生(ES5)

I have this error from TS:

It's pretty clear why the error occurs:

function outer(){

   if (true) {
        function inner(){    // nested function declaration

       }
   }   
}

but my question is - why does TS complain about that - is there some technical reason I should avoid nested function declarations when transpiling to ES5?

Would a function expression be a better choice, and why?

解决方案

Would a function expression be a better choice

Yes. The following is the way to go:

function outer() {
  if (true) {
    const inner = function() { // OK
    }
  }
}

Why?

  • ES modules are in strict mode by default.
  • strict mode does not allow function declarations in blocks

Reason why it was disallowed is covered in the original JavaScript specification. Short version: The behaviour was inconsistent between implementations.

NOTE Several widely used implementations of ECMAScript are known to support the use of FunctionDeclaration as a Statement. However there are significant and irreconcilable variations among the implementations in the semantics applied to such FunctionDeclarations. Because of these irreconcilable differences, the use of a FunctionDeclaration as a Statement results in code that is not reliably portable among implementations. It is recommended that ECMAScript implementations either disallow this usage of FunctionDeclaration or issue a warning when such a usage is encountered. Future editions of ECMAScript may define alternative portable means for declaring functions in a Statement context.

So when strict mode came into being (ES5) it made it disallowed.

这篇关于TS为什么在函数体内抱怨函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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