Lamda expressions and callback in TypeScript

Created by
Sunday, August 21, 2016

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. Please not that, (x) => x + 1 can be written as x => x + 1 however, consider maing your code more readable for other programmers.

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: 28
};
(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. Your feedback is important.

 

Cheers :-)

4
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
0 comments