admin管理员组文章数量:1423163
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 plain 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?
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 plain 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?
Share Improve this question edited Apr 19, 2017 at 5:40 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Apr 19, 2017 at 1:23 Alexander MillsAlexander Mills 101k166 gold badges538 silver badges919 bronze badges 2- 2 Possible Duplicate: stackoverflow./questions/10069204/… – SoEzPz Commented Apr 19, 2017 at 2:03
- Some useful links also here: stackoverflow./questions/33359840/… – Jevgeni Commented Apr 19, 2017 at 2:40
1 Answer
Reset to default 8Would 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 remended 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.
本文标签: javascriptWhy TS complains with function declarations inside function bodyStack Overflow
版权声明:本文标题:javascript - Why TS complains with function declarations inside function body - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745388154a2656469.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论