Open In App

TypeScript Anonymous Functions Type

In TypeScript, an Anonymous Function Type represents a function without a specific name. It defines the shape of functions by specifying parameter types and return types, allowing flexible and reusable function definitions.

Syntax

let functionName: (param1Type, param2Type, ...) =>
    returnType = function (param1, param2, ...) {
        // Function implementation here
    };

Parameters

Example 1: In this example, we declare the variable greet as an anonymous function type that takes a string parameter (name) and returns a string. We then assign a function that generates a greeting message, call it “GeeksforGeeks,” and log the result.






// Define the type of an anonymous function
let greet: (name: string) => string =
    function (name) {
        return `Hello, ${name}!`;
    };
  
// Call the function
const message = greet("GeeksforGeeks");
console.log(message);

Output:

Hello, GeeksforGeeks!

Example 2: In this example, a variable calculate is defined as a function taking number parameters x, y, and a string parameter operation, returning a number. An anonymous function performs mathematical operations based on the operation. The code then calls calculate with different arguments for addition and division, logging the results.






// Define the type of an anonymous
//  function with multiple parameters
let calculate: (x: number, y: number, operation: string) =>
    number = function (x, y, operation) {
        if (operation === "add") {
            return x + y;
        } else if (operation === "subtract") {
            return x - y;
        } else if (operation === "multiply") {
            return x * y;
        } else if (operation === "divide") {
            return x / y;
        } else {
            throw new Error("Invalid operation");
        }
    };
  
const result1 = calculate(5, 3, "add");
console.log(result1);
  
const result2 = calculate(10, 2, "divide");
console.log(result2);

Output:

8
5

Article Tags :