定义 TypeScript 回调类型 [英] Defining TypeScript callback type
问题描述
我在 TypeScript 中有以下类:
I've got the following class in TypeScript:
class CallbackTest
{
public myCallback;
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
我正在使用这样的类:
var test = new CallbackTest();
test.myCallback = () => alert("done");
test.doWork();
代码有效,所以它按预期显示了一个消息框.
The code works, so it displays a messagebox as expected.
我的问题是:我可以为我的类字段 myCallback
提供任何类型吗?现在,公共字段 myCallback
的类型为 any
,如上所示.如何定义回调的方法签名?或者我可以将类型设置为某种回调类型吗?或者我可以做这些吗?我是否必须使用 any
(隐式/显式)?
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.
推荐答案
我刚刚在 TypeScript 语言规范中找到了一些东西,它相当简单.我非常接近.
I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.
语法如下:
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;
这篇关于定义 TypeScript 回调类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!