Interface for functions in Typescript

Typescript is capable of defining Interfaces for functions. In this tutorial, we will learn how to define an interface for function types and use it.

Creating Interface for Function Types

To create an interface for function type use the keyword interface followed by the interface name. Then follow It up with curly brackets {}. Inside the curly braces { } add the list of parameters (comma-separated) inside parentheses. Follow it up with a semicolon : and return type.

In the following example, the Calculator is an interface that describes a function. The function takes two arguments and returns a number.

The parameter names need not match. Hence the above can also be written as follows. Note that we have used num1 & num2 instead of arg1 & arg2

But data types need not be the same but they must be compatible. For Example in the implementation function, you can use unknown or any as both are compatible with number type. But string or booleans are not allowed.

Typescript compiler throws an error if we try to use more arguments or arguments of incompatible data types to the implementation function.

But less number of arguments in the implementation function is ok.

Interface for functions Examples

The following are some of the examples of how you can create an interface for various function types.

This interface takes a single string argument and returns a string.

This interface takes no arguments and returns nothing

Takes an argument and returns nothing

The function with an optional argument. Note that if the interface declares an optional argument then the implementation function must also declare it as optional.

Similarly, the following examples show how you can create an interface for types that contain a function.

The function is optional here

The implementation function is not enforced to implement all the arguments

The Typescript does not enforce us to implement all the arguments of the interface. But the caller must supply all the required arguments.

In this example, the Calculator interface declares three arguments. But in the implementation function, we have omitted the third argument and the compiler does not complain.

But if we invoke the function with two arguments, the compiler will throw an error.

But note that the implementation function cannot use more arguments than specified in the interface.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top