Defining TypeScript callback type

后端 未结 8 1146
情话喂你
情话喂你 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: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;};
    

提交回复
热议问题