TypeScript Arrow function
ES6 version of TypeScript provides an arrow function which is the shorthand syntax for defining the anonymous function, i.e., for function expressions. It omits the function keyword. We can call it fat arrow (because -> is a thin arrow and => is a “fat” arrow). It is also called a Lambda function. The arrow function has lexical scoping of “this” keyword.
The motivation for arrow function is:
- When we don’t need to keep typing function.
- It lexically captures the meaning of this keyword.
- It lexically captures the meaning of arguments.
Syntax
We can split the syntax of an Arrow function into three parts:
- Parameters: A function may or may not have parameters.
- The arrow notation/lambda notation (=>)
- Statements: It represents the function’s instruction set.
If we use the fat arrow (=>) notation, there is no need to use the function keyword. Parameters are passed in the brackets (), and the function expression is enclosed within the curly brackets {}.
There are two ways of writing a function in ES5 and ES6 style of coding.
Arrow function with parameter
The following program is an example of arrow function with parameters.
In the above example, the sum is an arrow function, “a: number, b: number” is a parameter type, “: number” is the return type, the arrow notation => separates the function parameter and the function body.
After compiling the above TypeScript program, the corresponding JavaScript code is:
Output:
Arrow function without a parameter
The following program is an example of arrow function without parameters.
Output:
In the arrow function, if the function body consists of only one statement, then there is no need of the curly brackets and the return keyword. We can understand it from the below example.
Output:
Arrow function in a class
We can include the arrow function as a property in a class. The following example helps to understand it more clearly.
Output: