July 25, 2022

TypeScript: How to Pass a Function as a Parameter

In JavaScript you can pass the callback functions as parameters when triggering other functions. In this post, we will see an example how to do the same in TypeScript.

Let see the following code:

function f1(callback) {
  console.log('f1() function called!');
  callback();
}

function f2() {
  console.log('f2() function called!');
}

f1(f2);

In this exmaple, we have two functions f1() and f2(). We are passing f2() function as a callback paramter to function f1(), which will internally call the function f2().

It seems all ok in Javascript. However we are not leveraging the power of TypeScript.

If we pass anything (other than function, e.g. number) as a parameter to f1(), it will be compiled successfully but gives the runtime error. To avoid this issue, we can define the type of the callback parameter as Function.

So the f1() function will become:

function f1(callback: Function) {
  console.log('f1() function called!');
  callback();
}

Here f1() is enforcing the paramter should be of type Function. If you will pass anything other than the Function type, you will get compile error.

If you want to also use the return type of the callback function (lets say the return type will be number), then this solution will not work. Because the Function type could not enforce TypeScript to pass a function with desired return type.

For this, you can use an arrow function expression that returns a type to provide a valid type definition.

Let’s modify the definition of the f1() function.

function f1(callback: () => number) {
  console.log('f1() function called!');
  const number = callback();
  console.log('callback() function returns value: ' + number);
}

This helps the code to be more predictable with TypeScript, and prevent the unexpected runtime behavior often caused by lack of type definition.

No comments:

Post a Comment