简体   繁体   English

定义 TypeScript 回调类型

[英]Defining TypeScript callback type

I've got the following class in TypeScript:我在 TypeScript 中有以下 class:

class CallbackTest
{
    public myCallback;

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

I am using the class like this:我正在使用这样的 class:

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 ?我的问题是:我可以为我的 class 字段myCallback提供任何类型吗? Right now, the public field myCallback is of type any as shown above.现在,公共字段myCallback any类型如上所示。 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)?我必须使用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.我在网上找不到任何解释,所以我希望你能帮助我。

I just found something in the TypeScript language specification, it's fairly easy.我刚刚在 TypeScript 语言规范中找到了一些东西,这很容易。 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
    }
}

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;

You can declare a new type:您可以声明一个新类型:

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

var handler: MyHandler;

Update.更新。

The declare keyword is not necessary. declare关键字不是必需的。 It should be used in the .d.ts files or in similar cases.它应该用于 .d.ts 文件或类似情况。

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

If you want a generic function you can use the following.如果你想要一个通用函数,你可以使用以下内容。 Although it doesn't seem to be documented anywhere.虽然它似乎没有记录在任何地方。

class CallbackTest {
  myCallback: Function;
}   

You can use the following:您可以使用以下内容:

  1. Type Alias (using type keyword, aliasing a function literal)类型别名(使用type关键字,为函数字面量取别名)
  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;

    // ...

}

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

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.奇怪的是,将回调类型设置为 EventListener 就解决了。 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);
    }
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM