Why Ts Complains With Function Declarations Inside Function Body
Solution 1:
Would a function expression be a better choice
Yes. The following is the way to go:
functionouter() {
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.
Post a Comment for "Why Ts Complains With Function Declarations Inside Function Body"