This project is read-only.

Implicit return of object literal in lambdas

Topics: General, Language Specification
Mar 18, 2013 at 3:20 PM
With the way TS/JS declares object literals, there seems to be a syntax ambiguity when attempting to implicitly return object literals in a lambda.
var foo = 5;
var a = i => {i: i, foo: foo};
The compiler, of course, tries to parse the object as a function body and fails.

Is this a bug or is it not technically possible for the compiler to disambiguate whether the brackets denote a function body or an object literal with an implicit return? My suspicion is that without introducing additional syntax, the latter is probably true.

Side note, why implicitly returning object literals would be useful (LINQ):
var myObj = enumerable
    .SelectMany(a => a, (a,b) => {a: a, b: b})
    .Where(anon => anon.a === 5 && anon.b === 'foo')
Mar 18, 2013 at 3:41 PM
I think adding parenthesis would solve the problem?
var foo = 5;
var a = i => ({i: i, foo: foo});
Mar 18, 2013 at 4:23 PM
Yes, this works. I didn't think of that workaround.

I think the original question remains though, which is whether it's possible (or even worth it) for the compiler to try and differentiate a function body/object in the absence of parenthesis.
Mar 18, 2013 at 8:28 PM
Note that JavaScript itself has the same syntactic ambiguity - this could either be a Labelled Statement inside a Block, or an ExpressionStatement consisting of an object literal.
if(x < 4) {
    a: foo()
We follow the same pattern and always assume { } indicates a Block where an ambiguity could exist.
Mar 18, 2013 at 8:38 PM
Interesting. I hadn't considered that scenario with a label before.

Thanks for your response.