I\'ve got the following class in TypeScript:
class CallbackTest
{
public myCallback;
public doWork(): void
{
//doing some work...
You can use the following:
type
keyword, aliasing a function literal)Here is an example of how to use them:
type myCallbackType = (arg1: string, arg2: boolean) => number;
interface myCallbackInterface { (arg1: string, arg2: boolean): number };
class CallbackTest
{
// ...
public myCallback2: myCallbackType;
public myCallback3: myCallbackInterface;
public myCallback1: (arg1: string, arg2: boolean) => number;
// ...
}
I came across the same error when trying to add the callback to an event listener. Strangely, setting the callback type to EventListener solved it. It looks more elegant than defining a whole function signature as a type, but I'm not sure if this is the correct way to do this.
class driving {
// the answer from this post - this works
// private callback: () => void;
// this also works!
private callback:EventListener;
constructor(){
this.callback = () => this.startJump();
window.addEventListener("keydown", this.callback);
}
startJump():void {
console.log("jump!");
window.removeEventListener("keydown", this.callback);
}
}