How to Pass Strongly-typed Functions as Parameters in TypeScript

Is it possible to pass stronglytyped functions as parameters in TypeScript? Yes, it is possible to use strongly-typed functions as parameters in TypeScript.

To pass strongly-typed functions as parameters in TypeScript, “define the function parameter type by specifying the input types and the return type“.

Example

Suppose you want a function execute that accepts a callback function. The callback function should take a string as input and return a number.

function execute(callback: (input: string) => number) {
  const input = "Hello, TypeScript!";
  const result = callback(input);
  console.log("Result:", result);
}

function myCallback(input: string): number {
  return input.length;
}

execute(myCallback);

Output

Result: 18

In this code example, the callback is a strongly-typed function parameter of type (input: string) => number, which means it is a function that takes a string as input and returns a number.

Using strongly-typed functions as parameters ensures that the functions passed as arguments have the correct input and output types, providing better type safety and making the code easier to understand and maintain.

Leave a Comment