Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Typescript lambda function gets broken by curly braces?

I started developing Typescript & C# not long ago, while formerly most of my development was with javascript+php. I am developing an angular 2 app, and created an HTTP service. The problem I am discussing here has more to do with Typescript than with angular 2.

in the following code:

 export class HttpRest{
 constructor(
        private _http: Http,
        private userIdsx: UserIds,
        private _jsonFormater: JsonFormater
 ){}
 ...
 getGroupsList(){
    return this._http.get('file.json')
        .map(res => res.json());
 }
...
}

I am passing an anonymous lambda function with a single statement, and i want to add curly braces to create a function scope, but when I do that things get broken.

Im trying to refactor:

.map(res => res.json());

To:

.map((res) => {
    res.json()
});

So I could do more operations, but this brakes the code and results in an undefined error on the JSON object that is defined by res.json().

The question is, why does adding curly braces brakes this simple function? Isn't lambda functions with scope curly braces a built in feature of the language?

like image 242
wagwanJahMan Avatar asked Aug 15 '26 05:08

wagwanJahMan


1 Answers

Use the following. You need to return something.

.map((res) => {
  return res.json()
});

With the concise body version (without curly brackets), it's implicitly done...

like image 113
Thierry Templier Avatar answered Aug 17 '26 18:08

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!