Are strongly-typed functions as parameters possible in TypeScript?

Sure. A function’s type consists of the types of its argument and its return type. Here we specify that the callback parameter’s type must be “function that accepts a number and returns type any“:

class Foo {
    save(callback: (n: number) => any) : void {
        callback(42);
    }
}
var foo = new Foo();

var strCallback = (result: string) : void => {
    alert(result);
}
var numCallback = (result: number) : void => {
    alert(result.toString());
}

foo.save(strCallback); // not OK
foo.save(numCallback); // OK

If you want, you can define a type alias to encapsulate this:

type NumberCallback = (n: number) => any;

class Foo {
    // Equivalent
    save(callback: NumberCallback) : void {
        callback(42);
    }
}

Leave a Comment