Passing Functions as Parameters in TypeScript

Introduction

In TypeScript, functions are first-class citizens, which means they can be assigned to variables, stored in data structures, and even passed as parameters to other functions.

This Byte will explore how to pass functions as parameters in TypeScript, discuss type aliasing for functions, and see how to check function types with the typeof keyword.

Passing Functions as Parameters

In TypeScript, you can pass a function as a parameter to another function just like any other variable. This provides a lot of flexibility in your code. We see this a lot in the form of callbacks.

Here is a simple example:

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

function processGreeting(name: string, fn: (a: string) => string): string {
    return fn(name);
}

console.log(processGreeting("StackAbuse", greet)); // Outputs: Hello, StackAbuse!

In the above example, processGreeting() is a function that accepts a string and a function as parameters. The passed function fn takes in a string as a parameter and return a string.

Type Aliasing for Functions

TypeScript provides a feature called "type aliasing" which allows you to create a new name for a type. This can be useful when dealing with complex types like functions. Here's how you can create a type alias for a function:

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

type GreetingFunction = (a: string) => string;

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

function processGreeting(name: string, fn: GreetingFunction): string {
    return fn(name);
}

console.log(processGreeting("StackAbuse", greet)); // Outputs: Hello, StackAbuse!

In the above example, GreetingFunction is a type alias for a function that takes a string parameter and returns a string. This makes the code more readable and easier to manage.

Inferencing Function Type with typeof

TypeScript can automatically infer the type of a function using the typeof keyword. This can be useful when you want to pass a function as a parameter but don't want to explicitly define its type:

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

function processGreeting(name: string, fn: typeof greet): string {
    return fn(name);
}

console.log(processGreeting("StackAbuse", greet)); // Outputs: Hello, StackAbuse!

Here, the type of the fn parameter in the processGreeting function is inferred to be the same as the type of the greet function using the typeof keyword.

Conclusion

In this Byte, we showed how to pass functions as parameters in TypeScript, how to use type aliasing for functions, and how to infer function types with the typeof keyword. These techniques can help make your TypeScript code more flexible, readable, and maintainable.

Last Updated: August 20th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms