TypeScript
In this tutorial we will learn about arrow functions in TypeScript.
An Arrow Function a.k.a. Fat Arrow Function, are concise way of writing a function expression.
In the following example we have two ways of writing a function in ES5 and ES6 style of coding.
// ES5 var getResult = function(username, points) { return username + ' scored ' + points + ' points!'; }; // ES6 var getResult = (username: string, points: number): string => { return `${ username } scored ${ points } points!`; }
To create an arrow function with no parameters and no return value we use the given syntax.
() => {}
In the following example we have a function fun1 that takes no arguments and returns no value.
fun1
var fun1 = () => { console.log("Hello World"); }; // calling fun1();
The above code is similar to the following.
var fun1 = function() { console.log("Hello World"); };
Following is the syntax of an arrow function having no parameters but returns some value.
(): type => { return expr; }
In the following example we have a function fun2 that takes no argument but returns a value of type number.
fun2
number
var fun2 = (): number => { return Math.random(); }; // calling console.log("Random number: " + fun2());
The above code is similar to the following code.
var fun2 = function() { return Math.random(); };
Following is the syntax of an arrow function having some parameters but returns no value.
(v1: type, v2: type, ...): void => {}
In the following example we have a function fun3 that takes two arguments (string and number) and returns no value.
fun3
var fun3 = (username: string, points: number): void => { let str = `${ username } scored ${ points } points!`; console.log(str); }; // calling fun3('Yusuf Shakeel', 10);
var fun3 = function(username, points) { var str = username + ' scored ' + points + ' points!'; console.log(str); };
Following is the syntax of an arrow function having some parameters and returning some value.
(v1: type, v2: type, ...): type => { return expr; }
In the following example we have a function fun4 that takes two arguments (string and number) and returns a string value.
fun4
var fun4 = (username: string, points: number): string => { return `${ username } scored ${ points } points!`; }; // calling console.log(fun4('Yusuf Shakeel', 10));
var fun4 = function(username, points) { return username + ' scored ' + points + ' points!'; };