Are strongly-typed functions as parameters possible in TypeScript?

Technology CommunityCategory: TypeScriptAre strongly-typed functions as parameters possible in TypeScript?
VietMX Staff asked 3 years ago
Problem

Consider the code:

class Foo {
    save(callback: Function) : void {
        //Do the save
        var result : number = 42; //We get a number from the save operation
        //Can I at compile-time ensure the callback accepts a single parameter of type number somehow?
        callback(result);
    }
}

var foo = new Foo();
var callback = (result: string) : void => {
    alert(result);
}
foo.save(callback);

Can you make the result parameter in save a type-safe function? Rewrite the code to demonstrate.

In TypeScript you can declare your callback type like:

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

class Foo {
    // Equivalent
    save(callback: NumberCallback): void {
        console.log(1)
        callback(42);
    }
}

var numCallback: NumberCallback = (result: number) : void => {
    console.log("numCallback: ", result.toString());
}

var foo = new Foo();
foo.save(numCallback)