HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

Defining TypeScript callback type

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
callbacktypescripttypedefining

Problem

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.

Solution

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;

Code Snippets

public myCallback: (name: type) => returntype;
class CallbackTest
{
    public myCallback: () => void;

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}
type MyCallback = (name: type) => returntype;

Context

Stack Overflow Q#13137350, score: 336

Revisions (0)

No revisions yet.