Programming

Higher-Order Functions With TypeScript

Introduction

TypeScript is not a purely functional programming language but offers a lot of concepts that are in line with functional programming languages. Most developers are oblivious to these concepts in TypeScript.

 

A Higher-order-function is a function that accepts one or more functions as parameters or returns another function as a result. 



What are Higher-Order Functions?

A Higher-Order Function is a function that either takes another function as an argument or returns a function. So basically we could say, that a Higher-Order Function is wrapping another function. 

 

Example of a higher-order function;

const numbers = [1, 2, 3, 4, 5];
 
function addOne(array) {
  for (let i = 0; i < array.length; i++) {
    console.log(array[i] + 1);
  }
}

addOne(numbers);

Creating a Higher-Order Function

Higher-order functions provide a higher level of abstraction for functions.

 

Step One

The returned function’s argument must be of the same type as the callback’s argument. You could set the type of the callback and arguments as static but then this wouldn’t be a reusable function.

const cacheResource = <CallbackFunction extends Function>(callback: CallbackFunction, key: string) => (...args: any[]) => {
    return callback(...args);
}

const getUser = (id: string) => ({ name: 'Dude' });

const cachedGetUser = cacheResource(getUser, 'user'); // (...args: any[]) => any

Step Two

To get TypeScript to infer the type from the callback function we need to connect the type assertions. We need to say that the returned function arguments and return are the same as the CallbackFunction.

const cacheResource = <CallbackFunction extends (...args: any) => any>(callback: CallbackFunction, key: string) => (...args: Parameters<CallbackFunction>): ReturnType<CallbackFunction> => {
    return callback(...args);
}

Step Three

The last part is making sure you set the callback as a promise. For this, we need to set the return types as Promises.

type ReturnPromiseType<T extends (...args: any) => Promise<any>> = T extends (...args: any) => Promise<infer R> ? R : any;

const cacheResource = <CallbackFunction extends (...args: any[]) => Promise<any>>(callback: CallbackFunction, key: string) => async (...args: Parameters<CallbackFunction>): Promise<ReturnPromiseType<CallbackFunction>> => {
    const data = await callback(...args);
    return data;
}

const getUser = (id: string) => Promise.resolve({ name: 'Dude' });

const cachedGetUser = cacheResource(getUser, 'user'); // (id: string) => Promise<{ name: string; }>

Conclusion

In TypeScript, functions can be passed as arguments to another function. Functions can also be returned by another function. A function passed to another as an argument is known as a callback. A function that accepts functions as parameters (callbacks) or returns functions is known as a higher-order function. A higher-order function takes at least a function as its argument(s) and returns a new function.

Michael Samuels

Michael is an accomplished Unity and C# game developer. He created a networking protocol for gamified playground equipment, served as the CTO of an educational gaming startup, and was a game developer on a multinational social-casino team.

Recent Posts

Blockchain in Elections: A Leap Toward Transparent Democracy

In 2024 we're witnessing a critical point in democratic technology: the integration of blockchain and…

3 weeks ago

Win Big with Our Amazon Fire Max 11 & AirPods Pro Giveaway!

We’re thrilled to announce an exciting opportunity for you to win not one but two…

2 months ago

Unleashing Potential: How Education Ecosystem Transforms Learning into Real-World Success

Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…

4 months ago

The Role of Artificial Intelligence in Modern Software Development

Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…

7 months ago

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

8 months ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

9 months ago