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
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.
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.
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.
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With