I\'ve got the following class in TypeScript:
class CallbackTest
{
public myCallback;
public doWork(): void
{
//doing some work...
If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.
class CallbackTest {
myCallback: Function;
}
I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.
the syntax is the following:
public myCallback: (name: type) => returntype;
In my example, it would be
class CallbackTest
{
public myCallback: () => void;
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
You can declare a new type:
declare type MyHandler = (myArgument: string) => void;
var handler: MyHandler;
The declare
keyword is not necessary. It should be used in the .d.ts files or in similar cases.
To go one step further, you could declare a type pointer to a function signature like:
interface myCallbackType { (myArgument: string): void }
and use it like this:
public myCallback : myCallbackType;
I'm a little late, but, since some time ago in TypeScript you can define the type of callback with
type MyCallback = (KeyboardEvent) => void;
Example of use:
this.addEvent(document, "keydown", (e) => {
if (e.keyCode === 1) {
e.preventDefault();
}
});
addEvent(element, eventName, callback: MyCallback) {
element.addEventListener(eventName, callback, false);
}
Here is an example - accepting no parameters and returning nothing.
class CallbackTest
{
public myCallback: {(): void;};
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
var test = new CallbackTest();
test.myCallback = () => alert("done");
test.doWork();
If you want to accept a parameter, you can add that too:
public myCallback: {(msg: string): void;};
And if you want to return a value, you can add that also:
public myCallback: {(msg: string): number;};