Typescript: Lambda syntax different between returning primitive and returning object

Created on 31 Oct 2016  ·  1Comment  ·  Source: microsoft/TypeScript



TypeScript Version: 2.0.3 / nightly (2.1.0-dev.201xxxxx)

Code

// A *self-contained* demonstration of the problem follows...
const fn_prim = () => 3;
const fn_obj = () => {
    val: 3
};

Expected behavior:
I expect it to compile fine. fn_prim should return 3 when called, fn_obj should return { val: 3 } when called.

Actual behavior:
"Unused label" error on val:

Question

Most helpful comment

TypeScript follows ES spec and per spec your second example is an arrow function where body is a function body wrapped in { } so val: 3 is interpreted as labelled statement with label val and expression statement with expression 3. In order to make it an arrow function that returns an object literal you'll need to wrap it in parens:

const fn_obj = () => ({
    val: 3
});

Related link: MDN: Arrow functions, section Returning object literals

>All comments

TypeScript follows ES spec and per spec your second example is an arrow function where body is a function body wrapped in { } so val: 3 is interpreted as labelled statement with label val and expression statement with expression 3. In order to make it an arrow function that returns an object literal you'll need to wrap it in parens:

const fn_obj = () => ({
    val: 3
});

Related link: MDN: Arrow functions, section Returning object literals

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DanielRosenwasser picture DanielRosenwasser  ·  3Comments

zhuravlikjb picture zhuravlikjb  ·  3Comments

wmaurer picture wmaurer  ·  3Comments

fwanicka picture fwanicka  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments