January 24, 2023

TypeScript - Function as a parameter

Sometimes we need to pass a function as a parameter to another function, which will internally call the parameter function.

Lets see an example how we can receive a function as a parameter.

We have to define the parameter type as Function.

function shipOrder(func: Function): void {
   //some logic
   console.log("shipOrder function is called");
	
   //call the function which is passed a parameter
   func();
}

Lets say we have a function getBillingAddress as follows:

getBillingAddress() {
   //some logic
   console.log("getBillingAddress function is called");
}

shipOrder is the function which will accept another function as a parameter, and then internally call this function. Since getBillingAddress accepts not parameter and returns void, we can simply invoke the function by its name alongwith paranthesis.

This is how we will call the shipOrder function by passing the function name as parameter.

shipOrder(getBillingAddress);

We can make it easier to read, define an interface describing the function signature that need to pass as paramter:

interface IFunction {
(): void;
}

The shipOrder function will become like this:

function shipOrder(func: IFunction): void {
   //some logic
   console.log("shipOrder function is called");
	
   //call the function which is passed a parameter
   func();
}

Since IFunction interface contains a function, with not paramters and void return type. Passing our old getBillingAddress function is still valid because of same function signature.

shipOrder(getBillingAddress);

We can also specify the paramters and return type for the function. Lets define a new interface:

interface INumberFunction {
(num: number): string;
}

Change the paramter type to INumberFunction

function shipOrder(func: INumberFunction): void {
   //some logic
   console.log("shipOrder function is called");
	
   //call the function which is passed a parameter
   //now the func is of type INumberFunction, we need to pass a number paramter and it will return a string.
   let someValue: string = func(1);
}

Calling the function and passing parameter is same.

shipOrder(getBillingAddress);

But when you need to invoke the actual function (which is passed a paramter), you have to take care of its signature, the required paramters and return type.

   let someValue: string = func(1);

No comments:

Post a Comment