What are Arrow/lambda functions in TypeScript ?
Arrow functions in TypeScript (also known as lambda functions) are concise and lightweight function expressions using the => syntax.
- Provide a shorter syntax for defining functions.
- Automatically bind the context of their surrounding scope.
- It is commonly used for callbacks, array methods, and simple one-liner functions.
Syntax:
(param1, param2, ..., paramN) => expression; //Arrow function having multiple parameters
() => expressions; //Arrow function with no parameters
const greet = (name: string): string => `Hello, ${name}!`;
console.log(greet("Alice"));
Output:
Hello, Alice!
More Example of Arrow function in TypeScript
Arrow Function in a Class
class Calculator {
add = (a: number, b: number): number => a + b;
}
const calc = new Calculator();
console.log(calc.add(5, 3));
- The Calculator class includes an add method defined as an arrow function, which takes two numbers and returns their sum.
- Using an arrow function ensures that the method inherits the this context from its enclosing class.
Output:
8
Arrow Function with Array Methods
const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(n => n * n);
console.log(squared);
- An arrow function is used within the map method to square each number in the numbers array.
- This concise syntax enhances readability when performing operations on array elements.
Output:
[1, 4, 9, 16, 25]
Arrow Function as a Callback
setTimeout(() => {
console.log("This message is displayed after 1 second.");
}, 1000);
- An arrow function is passed as a callback to setTimeout, which logs a message after a 1-second delay.
- Arrow functions are ideal for inline callbacks due to their concise syntax and lexical this binding.
Output:
This message is displayed after 1 second.
Best Practices for Using Arrow Functions in TypeScript
- Use Arrow Functions for Short Callbacks: Arrow functions are ideal for short and concise callback functions in methods like map, filter, and reduce.
- Avoid Arrow Functions for Methods in Classes: Use regular functions for class methods that require dynamic this binding, as arrow functions inherit the this context.
- Return Object Literals Correctly: Wrap object literals in parentheses when returning them in single-line arrow functions to avoid syntax errors.
- Use Arrow Functions to Maintain this Context: Arrow functions are useful in scenarios where you want to preserve the this context in event handlers or asynchronous code.