TypeScript Lambda Expressions
TypeScript Lambda Expressions
In TypeScript, a lambda expression is a concise syntax form used to define anonymous functions. Lambda expressions are typically used to pass functions as arguments or to create new functions within another function body.
Lambda expressions use arrow syntax (=>) to define functions, where the left side of the arrow specifies the parameter list and the right side specifies the function body. For example:
// Lambda expression as a function argument
const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = numbers.map((num) => num * 2);
console.log(doubleNumbers); // [2, 4, 6, 8, 10]
// Lambda expression to create a new function
const makeAdder = (x: number) => (y: number) => x + y;
const add5 = makeAdder(5);
console.log(add5(3)); // 8
In the first example, the map() function accepts a function as an argument to transform each element of the array. The lambda expression (num) => num * 2 defines a function that multiplies the passed parameter by 2.
In the second example, a lambda expression is used to create a function that returns another function, which in turn returns the sum of two numbers. This structure facilitates easy addition operations with different numbers.
Lambda expressions in TypeScript also support type annotations; arrow syntax can be used to specify the types of function parameters and return values. For example:
const addNumbers = (x: number, y: number): number => x + y;
console.log(addNumbers(2, 3)); // 5
In this example, the lambda expression (x: number, y: number): number => x + y defines a function that accepts two numbers and returns their sum. Both the parameter types and the return type are annotated as number.