Defining TypeScript callback type

后端 未结 8 1137
情话喂你
情话喂你 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:21

    You can use the following:

    1. Type Alias (using type keyword, aliasing a function literal)
    2. Interface
    3. 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;
    
        // ...
    
    }
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题