Categories
TypeScript Answers

How to create a function interface with TypeScript?

Spread the love

Sometimes, we want to create a function interface with TypeScript.

In this article, we’ll look at how to create a function interface with TypeScript.

How to create a function interface with TypeScript?

To create a function interface with TypeScript, we can put the signature and return type of the function in an interface.

For instance, we write

interface IFormatter {
  (data: string, toUpper: boolean): string;
}

const upperCaseFormatter: IFormatter = (data: string) => {
  return data.toUpperCase();
};

to create the IFormatter interface that requires a function to have signature that some or all of the parameters in (data: string, toUpper: boolean) and returns a string.

We can then create the upperCaseFormatter function with type IFormatter and with the data string parameter and returns a string.

Conclusion

To create a function interface with TypeScript, we can put the signature and return type of the function in an interface.

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 *