定义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
}
}
这篇关于定义TypeScript回调类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!