Higher-order functions
Relay calls services that fail, are slow, or must not be called twice: a queue, an upstream API, a notifier. The same handling keeps coming back. Run a setup step once. Cache a lookup. Count calls for a metric. Compute how long to wait before a retry. Each is a function that takes a function, or returns one.
The type problem is that the wrapper must not blur the wrapped function. If once(parsePort) is
typed as “some function”, the caller can pass a number to it and get anything back. This lesson
writes wrappers whose result has exactly the signature of the input.
Functions that return functions
Section titled “Functions that return functions”A function can return another function that remembers its arguments. That’s a closure. It’s how you configure something once and use it many times:
function makeLogger(prefix: string) { return (message: string): string => `[${prefix}] ${message}`}
const log = makeLogger("queue") // (message: string) => stringlog("connected") // "[queue] connected"The inferred type of makeLogger is (prefix: string) => (message: string) => string. Nothing
special is needed: arrow types nest.
Wrappers that keep the signature
Section titled “Wrappers that keep the signature”Here is a wrapper that counts calls, written the quick way:
function withCountLoose(f: Function) { let calls = 0 return (...args: any[]) => { calls += 1 return f(...args) }}
const parsePort = (raw: string): number => Number(raw)const counted = withCountLoose(parsePort) // (...args: any[]) => anycounted(42) // compiles, and returns anyFunction accepts any function but says nothing about it, and any[] and any turn the result
into “anything goes”. The caller just passed a number where parsePort wants a string, and the
compiler agreed.
The fix is to capture the argument list and the return type as type parameters:
function withCount<A extends unknown[], R>(f: (...args: A) => R) { let calls = 0 return (...args: A): R => { calls += 1 return f(...args) }}
const parsePort = (raw: string): number => Number(raw)const counted = withCount(parsePort) // (raw: string) => number
// @ts-expect-error: Argument of type 'number' is not assignable to parameter of type 'string'counted(42)A extends unknown[] is a rest-tuple type parameter. Matching (raw: string) => number against
(...args: A) => R makes A the tuple [raw: string] and R the type number. Spreading A
back into the returned function reproduces the parameters: names, optional ones, rest parameters.
Use unknown[] as the bound. any[] would also work, but it is the loose escape hatch you are
replacing.
Parameters and ReturnType
Section titled “Parameters and ReturnType”Sometimes you hold a function type and want pieces of it. Two built-in utility types do that:
function fetchJob(id: string, retries: number): Promise<{ id: string }> { return Promise.resolve({ id })}
type Args = Parameters<typeof fetchJob> // [id: string, retries: number]type Out = ReturnType<typeof fetchJob> // Promise<{ id: string }>Parameters<F> is the argument tuple and ReturnType<F> is what the function returns. M4 shows
how they are built. In a wrapper you rarely need them: naming A and R as type parameters, as
above, is more direct.
Currying and partial application
Section titled “Currying and partial application”A curried function takes its arguments one at a time and returns a function for the rest. It pays off when the first arguments are configuration and the last is data, so you configure once and use many times. Relay’s retry delay is a good case:
const retryAfter = (baseMs: number) => (factor: number) => (attempt: number): number => baseMs * factor ** attempt
const upstream = retryAfter(100)(2) // (attempt: number) => numberconst delays = [0, 1, 2, 3].map(upstream) // [100, 200, 400, 800]upstream is a policy for one service. It can be passed to map, stored, or given to a retry loop
that only knows about attempts. Currying is noise when there is no natural “configure first” order,
or when nobody ever uses the intermediate functions: add(1)(2) is just a harder way to say
add(1, 2). Curry the arguments that stay the same across many calls.
this is lost in wrappers
Section titled “this is lost in wrappers”The wrappers above call f(...args) with no receiver. A method that uses this breaks when it is
wrapped, the same loss the functions lesson showed for a method pulled off its
object:
class Notifier { prefix = "notify" send(message: string): string { return `${this.prefix}: ${message}` }}
const notifier = new Notifier()function twice<A extends unknown[], R>(f: (...args: A) => R) { return (...args: A): [R, R] => [f(...args), f(...args)]}
twice(notifier.send)("hi") // compiles, then throws: 'this' is undefined inside sendtwice((m: string) => notifier.send(m))("hi") // fine: the arrow function keeps the receiverThe compiler does not warn about the first call, because send doesn’t declare a this parameter. If it did (send(this: Notifier, ...)),
the compiler would catch it, as in that lesson.
Wrap the method in an arrow function that keeps the receiver, or bind it first.
Exercise
Section titled “Exercise”Four wrappers for Relay’s service calls. The starter types them as Function and any, so
once(parsePort) accepts a number and returns any. Make once, memoize and withCount generic
so they keep their input’s signature, and implement the curried backoff. The capstone at the end
of the module uses backoff.
- A function can return a function. The closure remembers its configuration.
- To wrap a function without changing its type, capture its arguments and result:
<A extends unknown[], R>(f: (...args: A) => R) => (...args: A) => R. - Avoid
Functionandanyin wrappers. They make every call site unchecked. Parameters<F>andReturnType<F>take a function type apart. M4 shows how they are built.- Curry when you configure once and use many times. Skip it when the intermediate functions are never used.
- Wrappers call the function without a receiver, so
thisis lost. Wrap methods in an arrow function.
Further reading
Section titled “Further reading”- Handbook: Utility Types:
ParametersandReturnType. - this (MDN): how
thisis set, and lost. - Handbook: More on Functions: function types and
thisparameters.