How to Pass a Function as a Parameter in TypeScript?

Recently, someone asked me to provide an example of passing a function as a parameter in TypeScript. This is an interesting topic. In this tutorial, I will explain how to pass a function as a parameter in TypeScript with some examples.

Pass a Function as a Parameter in TypeScript

In TypeScript, functions are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned from functions. This capability is crucial for writing clean, modular code.

Now, let me show you some examples.

Basic Example

Let’s start with a basic example. Suppose we have a function that greets a user, and we want to pass this greeting function as a parameter to another function that logs the greeting.

function greetUser(name: string): string {
    return `Hello, ${name}!`;
}

function logGreeting(greetingFunction: (name: string) => string, userName: string): void {
    console.log(greetingFunction(userName));
}

logGreeting(greetUser, "John Doe");

In this example, greetUser is a function that takes a name and returns a greeting string. The logGreeting function takes a greetingFunction and a userName, then logs the result of calling greetingFunction with userName.

I executed the above code using VS code, and you can see the output in the screenshot below:

Pass a Function as a Parameter in TypeScript

Read How to Use Generic Arrow Functions in TypeScript?

Advanced Example with Callbacks

Callbacks are a common use case for passing functions as parameters. Let’s create a more advanced example where we simulate an asynchronous operation, such as fetching user data, and then process that data with a callback function.

interface User {
    firstName: string;
    lastName: string;
}

function fetchUserData(userId: number, callback: (user: User) => void): void {
    // Simulate an API call
    setTimeout(() => {
        const user: User = { firstName: "Jane", lastName: "Smith" };
        callback(user);
    }, 1000);
}

function displayUser(user: User): void {
    console.log(`User: ${user.firstName} ${user.lastName}`);
}

fetchUserData(1, displayUser);

In this example, fetchUserData simulates an API call that fetches user data and then calls the callback function with the fetched user data. The displayUser function is passed as the callback to fetchUserData.

Read Get Return Type of a Function in TypeScript

Pass Functions with Multiple Parameters

Sometimes, the function you want to pass as a parameter takes multiple arguments. Here’s how you can handle that:

function calculateTotal(price: number, tax: number): number {
    return price + tax;
}

function processTransaction(transactionFunction: (price: number, tax: number) => number, price: number, tax: number): void {
    const total = transactionFunction(price, tax);
    console.log(`Total amount: $${total}`);
}

processTransaction(calculateTotal, 100, 8.25);

In this example, calculateTotal takes two parameters, price and tax, and returns the total amount. The processTransaction function takes transactionFunction, price, and tax as parameters and logs the total amount.

Here is the output in the screenshot below:

Pass Functions with Multiple Parameters in TypeScript

Read How to Handle Catch Error Types in TypeScript?

Using Arrow Functions

Arrow functions provide a concise syntax for writing functions. They are particularly useful when passing simple functions as parameters.

Let me show you an example.

const users = ["Alice", "Bob", "Charlie"];

function processUsers(users: string[], processFunction: (user: string) => void): void {
    users.forEach(processFunction);
}

processUsers(users, (user) => console.log(`Processing user: ${user}`));

In this example, we use an arrow function as the processFunction parameter in processUsers. This makes the code shorter and more readable.

Here is the exact output in the screenshot below:

How to Pass a Function as a Parameter in TypeScript

Conclusion

In this tutorial, I explained how to pass functions as parameters in TypeScript with a few examples.

You may also like: