问题描述
来自 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 没有委托类型,但只有 lambdas.我想出了这样的事情:
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) =>void
几次,并认为创建自定义类型会更简洁 - 就像 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#.
有什么想法可以做到这一点吗?
Any ideas how this can be done?
推荐答案
在 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 中声明一个委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!