Is it possible to pass strongly-typed functions as parameters in TypeScript?

Is it possible to pass strongly-typed functions as parameters in TypeScript?

In TypeScript, I can declare a parameter of a function as a type Function. However, is there a type-safe way to do this? For instance, consider the following example:

class Foo {
    save(callback: Function): void {
        // Perform save operation
        var result: number = 42; // The save operation returns a number
        // Is there a way to ensure at compile-time that the callback accepts a single parameter of type number?
        callback(result);
    }
}

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

In this example, the save callback is not type-safe. I’m passing a callback function where the function’s parameter is a string, but the save method passes a number, and the code compiles without errors. Is there a way to make the save method type-safe when passing a function as a parameter?

Is there an equivalent of a .NET delegate in TypeScript pass function as parameter ?

You can use generics to enforce type safety for the callback function’s parameter. By defining a generic type, you ensure that the callback function receives a parameter of the correct type.

class Foo {
    save<T>(callback: (result: T) => void, result: T): void {
        // Pass the result to the callback
        callback(result);
    }
}

const foo = new Foo();
const callback = (result: number): void => {
    alert(result);
};
foo.save(callback, 42); // Type-safe, as the callback expects a number

Instead of using Function as the type for the callback, you can define a specific type that includes the expected parameter type. This approach makes the save method type-safe.

type SaveCallback = (result: number) => void;

class Foo {
    save(callback: SaveCallback): void {
        // Pass the result to the callback
        const result: number = 42;
        callback(result);
    }
}

const foo = new Foo();
const callback: SaveCallback = (result) => {
    alert(result);
};
foo.save(callback); // Type-safe, as the callback expects a number

You can directly annotate the callback function with the expected parameter type when defining it. This ensures that the callback function adheres to the expected signature.

class Foo {
    save(callback: (result: number) => void): void {
        // Pass the result to the callback
        const result: number = 42;
        callback(result);
    }
}

const foo = new Foo();
foo.save((result: number) => {
    alert(result);
}); // Type-safe, as the callback expects a number