/ Programming

How to Type a Higher Order Function in Typescript

Given a higher order function like the following:

function higherOrderFunction(a:number, b: number) {
    return (a: number): number => {
        return a*b
    }
} 

This causes a problem when typing the function as typing in the usual way does not work.

We could type it as a Function, this is valid, but ambiguous.

Extending Function allows us to create a non-ambiguous type for the function

interface HigherOrderFunction extends Function {
    (a:number): number
}

Our final result with typing:

interface HigherOrderFunction extends Function {
    (a:number): number
}

function higherOrderFunction(b: number): HigherOrderFunction {
    return (a: number): number => {
        return a * b
    };
}