Defining TypeScript callback type

后端 未结 8 1112
情话喂你
情话喂你 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 11:57

    If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.

    class CallbackTest {
      myCallback: Function;
    }   
    
    0 讨论(0)
  • 2020-12-12 12:02

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-12 12:04

    You can declare a new type:

    declare type MyHandler = (myArgument: string) => void;
    
    var handler: MyHandler;
    

    Update.

    The declare keyword is not necessary. It should be used in the .d.ts files or in similar cases.

    0 讨论(0)
  • 2020-12-12 12:05

    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;
    
    0 讨论(0)
  • 2020-12-12 12:11

    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);
    }
    
    0 讨论(0)
  • 2020-12-12 12:19

    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;};
    
    0 讨论(0)
提交回复
热议问题