This is very Important concept you need to know when using TypeScript to build Angular or React Applications is the concept of using Arrow functions
Table of Contents
How to declare a function in JavaScript?
First Let’s see how we can declare function in javascript and then will see arrow function next.
var test = function(message) {
console.log(message);
};
So as you can in JavaScript we can declare a function like showing in above code, we are using a function keyword to assign function to test variable and we have opening and closing curly brackets to enclosed the functions statements.
Next’s let’s see how to declare a function in Typescript.
How to declare arrow function in TypeScript?
So in Typescript there is modern and shorter way of define a function, let’s define the same function by renaming to testLog.
Arrow Function with Parameters
let testLog = (message) => {
console.log(message);
};
So as you can see we have testLog variable and we don’t need a function keyword here, we can simple add the parameters inside parenthesis, here in this case we are adding message parameter,
Next we have arrow “=>” after the parameter and that’ why we call this function arrow function and next to array function we added a code block using opening and closing curly brackets.
Single line Function:
So if our function has only one line inside code block we can exclude the currely brackets, like showing below:
let testLog = (message) => console.log(message);
If you have worked with C# (sharp) language, you might have seen this before in C# we called this a lamda expression and in TypeScript we call it arrow function.
Important note:
If your function just has only one parameter, like we do have only one parameter here in the example above. We can even exclude the parenthesis I showing below:
let testLog = message => console.log(message);
I personally don’t like excluding parenthesis because I think it makes the code a little bit less readable, I always like to put my parenthesis for the arrows functions so it allows me indicate clearly that this are the parameter for this particular function.
Arrow Function without Parameters
So now what if your function is not having parameters, so you can simple add empty parenthesis and then arrow next to the parenthesis, for example:
let testLog = () => console.log('test');
Conclusion:
If you have not seen arrows function before so get used to it by reading this tutorial it is very nice and clean way of defining functions.
And Always remember to only use Curley brackets if your function has multiple line of code if not you can always exclude Curley brackets.
What’s Next?
Next let’s see another important concept from TypeScript called Interface, see this tutorial to learn about interface – What is Interface and How to use Interface in TypeScript?