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


基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01