Search code examples
javascriptnode.jstypescriptecmascript-5

Lambda in Typescript behaving weird


I have the following statement as part of a bigger class:

array.map(seq => this.mFunction(seq));

this compiles (with the help of tsc command) to:

array.map(function (seq) { return _this.mFunction(seq); });

Okay all looks good... But why does then:

array.map(seq => { this.mFunction(seq); });

compile into:

array.map(function (seq) { _this.mFunction(seq); });

I have actually gotten problems in a project where the first way of writing was OK but the second made the webpage break in lots of ways (I'm using Angular)... I always thought those were exactly the same..

This is from my tsconfig:

"module": "es2015",
"moduleResolution": "node",
"target": "es5"

Solution

  • If your lambda body isn't enclosed in braces, then the body is treated as an expression whose value is to be returned, so TypeScript adds a return keyword. If the lambda body is enclosed in braces, then the body is treated as a statement block to be executed, and you are responsible for including any necessary return keyword.