Open In App

TypeScript Anonymous Functions Type

Last Updated : 01 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • functionName: is the name of the variable where you’re defining the anonymous function type.
  • param1Type, param2Type, …: These are the data types of the function’s parameters. You should replace them with the actual data types your function expects.
  • returnType: is the type of the value that the function will return.
  • function(param1, param2, …): is the actual anonymous function you’re assigning to functionName.
  • param1, param2, …: These are the parameter names used within the anonymous function. They should match the parameter names specified in the type annotation

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.

Javascript




// 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.

Javascript




// 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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads