Defining TypeScript callback type

后端 未结 8 1140
情话喂你
情话喂你 2020-12-12 11:53

I\'ve got the following class in TypeScript:

class CallbackTest
{
    public myCallback;

    public doWork(): void
    {
        //doing some work...
               


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 12:23

    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);
        }
    }
    

提交回复
热议问题