在 Typescript 中声明一个委托类型

Declare a delegate type in Typescript(在 Typescript 中声明一个委托类型)
本文介绍了在 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 没有委托类型,但只有 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 中声明一个委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)