Typescript arrow function
Created By: chatGPT
In TypeScript, an arrow function (also known as a fat arrow function) is a concise way to write a function. Arrow functions differ from traditional function expressions in a few key ways, particularly in their handling of the 'this' keyword. They do not bind their own this, but inherit it from the enclosing context, which helps avoid confusion in many cases.
const add = (a: number, b: number): number => {
return a + b;
};
You can also write one-liner arrow functions, where the function body is a single expression. In this form, you can omit the curly braces and the return keyword.
const multiply = (a: number, b: number): number => a * b;
If you have only one parameter, you can omit the parentheses around the parameter. This makes the syntax even more concise.
const square = n: number => n * n;
Arrow functions can be particularly useful when passing functions as arguments. Here’s an example of using an arrow function as a callback in the Array.prototype.map() method:
In summary, arrow functions provide a modern and compact syntax for writing functions in TypeScript. They improve code readability while maintaining the correct context for 'this'.const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]