Dyna Dyna - 1 month ago 45x
TypeScript Question

Declare a delegate type in Typescript

Coming from a C# background, I want to create a datatype that defines a function signature. In C#, this is a

declared like this:

delegate void Greeter (string message);

public class Foo
public void SayHi (Greeter g) {

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) {

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?


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) {

sayHi((msg) => console.log(msg)); // msg is inferred as string