在Typescript中声明一个委托类型 [英] Declare a delegate type in Typescript
问题描述
来自C#背景,我想创建一个定义函数签名的数据类型。在C#中,这是这样的 delegate
声明:
Coming from a C# background, I want to create a datatype that defines a function signature. In C#, this is a delegate
declared like this:
delegate void Greeter (string message);
public class Foo
{
public void SayHi (Greeter g) {
g("Hi!");
}
}
现在,我想在Typescript中实现类似的功能。我知道Typescript没有委托类型,只有lambda。我想出了这样的东西:
Now, I want to achieve similar in Typescript. I know Typescript has no delegate types, but only lambdas. I came up with something like this:
class Foo {
SayHi (greeter: (msg: String) => void) {
greeter('Hi!');
}
}
虽然可行,但我想重用方法签名(msg:String)=> 无效
几次,并认为创建自定义类型(如C#中的委托)会更干净。
While this works, I want to reuse the method signature (msg:String) => void
couple of times and think it would be cleaner to create a custom type - like the delegate in C#.
任何想法都可以
推荐答案
在TypeScript中,接口可以具有调用签名。在您的示例中,您可以这样声明:
In TypeScript, interfaces can have call signatures. In your example, you could declare it like this:
interface Greeter {
(message: string): void;
}
function sayHi(greeter: Greeter) {
greeter('Hello!');
}
sayHi((msg) => console.log(msg)); // msg is inferred as string
这篇关于在Typescript中声明一个委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!