定义 TypeScript 回调类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13137350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:54:54  来源:igfitidea点击:

Defining TypeScript callback type

typescallbacktypescript

提问by nikeee

I've got the following class in TypeScript:

我在 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 myCallbackis of type anyas 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)?

我的问题是:我可以为我的班级字段提供任何类型myCallback吗?现在,公共字段myCallback的类型any如上所示。如何定义回调的方法签名?或者我可以将类型设置为某种回调类型吗?或者我可以做这些吗?我必须使用any(隐式/显式)吗?

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.

我在网上找不到任何解释,所以我希望你能帮助我。

回答by nikeee

I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.

我刚刚在 TypeScript 语言规范中找到了一些东西,这很容易。我非常接近。

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

回答by Leng

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;

回答by TSV

You can declare a new type:

您可以声明一个新类型:

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

var handler: MyHandler;

Update.

更新。

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

declare关键字是没有必要的。它应该用于 .d.ts 文件或类似情况。

回答by Fenton

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

回答by Ash Blue

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

如果你想要一个通用函数,你可以使用以下内容。虽然它似乎没有记录在任何地方。

class CallbackTest {
  myCallback: Function;
}   

回答by Willem van der Veen

You can use the following:

您可以使用以下内容:

  1. Type Alias (using typekeyword, aliasing a function literal)
  2. Interface
  3. Function Literal
  1. 类型别名(使用type关键字,为函数字面量取别名)
  2. 界面
  3. 函数字面量


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;

    // ...

}

回答by Daniel

I'm a little late, but, since some time ago in TypeScript you can define the type of callback with

我有点晚了,但是,因为前段时间在 TypeScript 中,您可以使用以下命令定义回调类型

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

回答by Kokodoko

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.

尝试将回调添加到事件侦听器时遇到了同样的错误。奇怪的是,将回调类型设置为 EventListener 就解决了。它看起来比将整个函数签名定义为类型更优雅,但我不确定这是否是正确的方法。

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