Are strongly-typed functions as parameters possible in TypeScript?
Solution 1:
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);
}
}
Solution 2:
Here are TypeScript equivalents of some common .NET delegates:
interface Action<T>
{
(item: T): void;
}
interface Func<T,TResult>
{
(item: T): TResult;
}