Typescript: Immediately-Invoked Arrow Function Expressions

Created on 26 Aug 2015  路  7Comments  路  Source: microsoft/TypeScript

()=>{}();

The above _does not_ result in the invocation of the anonymous arrow function.

TypeScript's Playground presently generates the following output:

(function () { });
();

Babel, for contrast, generates the following output:

(function () {})();

It is perhaps worth noting that Esprima doesn't like this syntax.

cc @jdalton

By Design

Most helpful comment

@DanielRosenwasser Yes, that is a known bug in Babel (linked by @jdalton). So, for people wanting to do this the solution is simply to wrap the ArrowFunction in parens making it a MemberExpression, right:?

(() => {})();

All 7 comments

Generally you shouldn't use (or even look at :wink:) any js generated in the presence of TypeScript syntax errors; it's unlikely to work.

In a compliant ES6 runtime, this is a syntax error. Babel's doing you a misfavor by parsing this without error.

Specifically, in the ES6 spec, the production in question is _CallExpression_, whose target is super, a _MemberExpression_, or another _CallExpression_. An _ArrowFunction_ can never be derived from these productions, so this code is not valid, and is probably a bug on Babel's end

Trying to map similar IIFE patterns like (function() { }()) to arrow functions

// will error in native enviros
(() => {
    console.log('hi');
}())

but in TypeScript playground will produce:

// logs 'hi'
(function () {
    console.log('hi');
})();

\cc @bterlson

Related to https://github.com/babel/babel/issues/2118.

@DanielRosenwasser Yes, that is a known bug in Babel (linked by @jdalton). So, for people wanting to do this the solution is simply to wrap the ArrowFunction in parens making it a MemberExpression, right:?

(() => {})();

@jmm correct.

@DanielRosenwasser Awesome, thanks.

thanks :)

Was this page helpful?
0 / 5 - 0 ratings