Defining TypeScript callback type

TypesCallbackTypescript

Types Problem Overview


I've got the following class in TypeScript:

class CallbackTest
{
    public myCallback;

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

I am using the class like this:

var test = new CallbackTest();
test.myCallback = () => alert("done");
test.doWork();

The code works, so it displays a messagebox as expected.

My question is: Is there any type I can provide for my class field myCallback? Right now, the public field myCallback is of type any as shown above. How can I define the method signature of the callback? Or can I just set the type to some kind of callback-type? Or can I do nether of these? Do I have to use any (implicit/explicit)?

I tried something like this, but it did not work (compile-time error):

public myCallback: ();
// or:
public myCallback: function;

I couldn't find any explanation to this online, so I hope you can help me.

Types Solutions


Solution 1 - Types

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

As a type alias:

type MyCallback = (name: type) => returntype;

Solution 2 - Types

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;

Solution 3 - Types

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.

Solution 4 - Types

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

Solution 5 - Types

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

class CallbackTest {
  myCallback: Function;
}   

Solution 6 - Types

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;

    // ...

}

Solution 7 - Types

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

Solution 8 - Types

Here is a simple example of how I define interfaces that include a callback.

// interface containing the callback

interface AmazingInput {
    name: string
    callback: (string) => void  //defining the callback
}

// method being called

public saySomethingAmazing(data:AmazingInput) {
   setTimeout (() => {
     data.callback(data.name + ' this is Amazing!');
   }, 1000)

}

// create a parameter, based on the interface

let input:AmazingInput = {
    name: 'Joe Soap'
    callback: (message) => {
        console.log ('amazing message is:' + message);
    }
}

// call the method, pass in the parameter

saySomethingAmazing(input);

Solution 9 - Types

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

Solution 10 - Types

This is an example of optional callback function for angular component and service

    maincomponent(){
        const param = "xyz";
       this.service.mainServie(param, (response)=>{
        if(response){console.log("true");}
        else{console.log("false");}
      })
    }

//Service Component
    mainService(param: string, callback?){
      if(string === "xyz"){
        //call restApi 
        callback(true);
      }
    else{
        callback(false);
      }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnikeeeView Question on Stackoverflow
Solution 1 - TypesnikeeeView Answer on Stackoverflow
Solution 2 - TypesLengView Answer on Stackoverflow
Solution 3 - TypesTSVView Answer on Stackoverflow
Solution 4 - TypesFentonView Answer on Stackoverflow
Solution 5 - TypesAsh BlueView Answer on Stackoverflow
Solution 6 - TypesWillem van der VeenView Answer on Stackoverflow
Solution 7 - TypesDanielView Answer on Stackoverflow
Solution 8 - TypessparkyspiderView Answer on Stackoverflow
Solution 9 - TypesKokodokoView Answer on Stackoverflow
Solution 10 - Typesgurpreet singhView Answer on Stackoverflow