Programming

Higher-Order Functions With TypeScript

HIGHER ORDER FUNCTIONS

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;

[/crayon]

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.

[/crayon]

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.

[/crayon]

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.

[/crayon]

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
About author

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.