Typescript – Higher order function types

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?

These both work

interface NumberFunction extends Function {

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

function twoMoreThanYou(calculateANumber: NumberFunction):number {

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Chrome extension - retrieving global variable from webpage

Similar Posts