11. Higher-Order Functions and Callbacks
Activity 11.01: Higher-Order Pipe Function
Solution:
In this activity, we'll build a higher-order pipe
function that accepts functions as arguments, and composes them from left to right, returning a function that accepts the arguments of the first function, and returns the type of the last function. When the returned function is run, it iterates over the given functions, feeding the return value of each function to the next one:
- Let's start by defining a type definition for the supported functions to compose, a function that accepts one argument of type
T
and returns one of typeR
:type UnaryFunction<T, R> = T extends void ? () => R : (arg: T) => R;
As mentioned, we'll only support functions accepting up to one argument, for simplicity.
Note that in order to deal with the special case of 0 arguments, we need to check whether
T extends void
and returns a parameterless function. - Next, let's start...