Lamda expression and callback in TypeScript

I was tinkering with TypeScript recently in one of the projects and my experience with C# came handy and understood the concept in no time.

My javascript friends had hard time understanding the concept and the moment; I showed them the JS code; they know it already. Based on this observation, I thought of writing blogs seriously first time in my decade career.

So what is lamda expression in TypeScript? This is just ES6 and not TypeScript specific. Let’s observe the below JS function carefully.

(function (x) { return x + 1; });

Simple. Ha : – ). Now let’s look at the same function using lamda expression.

(x) => x + 1;

Look at this. This looks sexy and beautiful.

Let’s look at the short and sweet callback blocks with lamda expression.

export interface Employee {
firstname: string,
lastname: string,
address: string,
age: number
}

export class MyService {
show = (input: Employee, callback) => {
setTimeout(() => {
return callback(null, input.firstname);
}, 2000)
}
}

Observe line 2-5. Just TypeScript specific blocks. show function just accepts interface Employee and uses callback to return the output. ES5 blocks are below, which are self explanatory for JS ninjas.

“use strict”;
var app = require(‘./app’);
var emp = {
firstname: “Rakesh”,
lastname: “Gupta”,
address: “Pune”,
age: 30
};
(function (x) { return x + 1; });
var svc = new app.MyService();
console.log(“started”);
svc.show(emp, function (err, data) {
console.log(data);
});
console.log(“stopped”);

 

Hope this helps. If you have any queries, please reach out to me at rakesh@howbitswork.com.

Your feedback is important.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s