Categories
TypeScript Answers

How to declare a delegate type in TypeScript?

Spread the love

Sometimes, we want to declare a delegate type in TypeScript.

In this article, we’ll look at how to declare a delegate type in TypeScript.

How to declare a delegate type in TypeScript?

To declare a delegate type in TypeScript, we can define an interface that restricts the signature and return type of a function.

For instance, we write

interface Greeter {
  (message: string): void;
}

const sayHi = (greeter: Greeter) => {
  greeter("Hello!");
};

sayHi((msg) => console.log(msg));

to define the Greeter interface that has signature (message: string) and has the void return type.

Then we set the greeter parameter of the sayHi function to the Greeter type.

Therefore, greeter takes a string and returns nothing.

Conclusion

To declare a delegate type in TypeScript, we can define an interface that restricts the signature and return type of a function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *