Typescript - Higher order function types

13,708

These both work

interface NumberFunction extends Function {
    (n:number):number;
}

function twoMoreThanYou(calculateANumber: (n:number)=>number):number {
    ...
}

function twoMoreThanYou(calculateANumber: NumberFunction):number {
    ...
}
Share:
13,708

Related videos on Youtube

Sean Clark Hess
Author by

Sean Clark Hess

Principal at Orbital Labs

Updated on June 06, 2022

Comments

  • Sean Clark Hess
    Sean Clark Hess almost 2 years

    I'm getting really excited about TypeScript. How do you set the type of a function parameter?

    function twoMoreThanYou(calculateANumber: Function):number {
        return calculateANumber(4) + 2;
    }
    
    function double(n:number):number {
        return n*2;
    }
    
    console.log("TWO MORE", twoMoreThanYou(double))
    

    How can I type calculateANumber better? I'd like to specify that it must be a function that takes a number and returns a number.

    Can I then make an "interface" or some shorthand for that type so I can make my higher order function signatures more readable?

  • asawyer
    asawyer over 11 years
    You don't have to specify the return type for the twoMoreThanYou function with the NumberFunction interface. Type inference!