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 中声明一个委托类型
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
