Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest syntax for a TypeScript lambda that returns an object literal

Tags:

typescript

Consider the JavaScript function:

function(o) { return o.a; } 

In TypeScript, the following shorthand is equivalent:

o => o.a 

Is there a way to apply this shorthand to the following function?

function(o) { return { a: o.a, b: o.b }; } 

The obvious transformation does not work as the opening brace ({) is interpreted as indicating a block is required:

o => { a: o.a, b: o.b }                // doesn't work  o => { return { a: o.a, b: o.b }; }    // works 
like image 420
Drew Noakes Avatar asked Nov 04 '13 16:11

Drew Noakes


People also ask

How do you return an object literal?

Because of the very expressive nature of JavaScript, what we return from a function is really up to us. So, if we want to have a constructor function that returns an object literal, we can literally (sorry : – ) just use the “return” statement, and put an object on the other side of that.

How do you return an object literal from arrow?

There's no return statement. What you need to do is force the parser to treat the object literal as an expression so that it's not treated as a block statement.

Which code will return an object from an arrow function?

The most common and standard way of returning an object from an arrow function would be to use the longform syntax: const createMilkshake = (name) => { return { name, price: 499 }; }; const raspberry = createMilkshake('Raspberry'); // 'Raspberry' console.

What is lambda function in typescript?

The Arrow/ lambda function is a concise form of a normal function in Typescript. Arrow functions are also known as lambda functions. We use “=>” (arrow symbol) in the arrow function and we do not use the 'function' keyword. We can use this method when we want our code to be short and not call the function each time.


1 Answers

There isn't a way to make the grammar interpret the { as an object literal rather than a block statement in this context, but you can use parentheses to force it to be interpreted as an expression:

var x = (t) => ({ n: t }); 
like image 66
Ryan Cavanaugh Avatar answered Sep 21 '22 21:09

Ryan Cavanaugh