How To Describe A Function Typing Using An Interface In TypeScript

Antonin J. (they/them) - Jun 24 '19 - - Dev Community

I keep forgetting how to do this but TypeScript supports describing a function signature (its arguments and return) using an interface and it's not that difficult. For example, to describe a regular Node-style callback, you might write something like this:

interface NodeStyleCallback {
  (err, data): any
}
Enter fullscreen mode Exit fullscreen mode

The syntax is essentially a regular interface as you're used to and arguments in the parentheses with a return type:

interface SomeFunction {
  (arg1, arg2, arg3, arg4): any
}

function someFunction(arg1, arg2, arg3, arg4) {
 // doesn't matter what the return, it'll always satisfy `any`
}
Enter fullscreen mode Exit fullscreen mode

You can also assign types to the arguments!

interface Sum {
  (arg1: number, arg2: number): number
}
Enter fullscreen mode Exit fullscreen mode

And while you can't assign an interface to a function, you can use the interface to describe variables -- include arguments like so:

interface IObject {
  [key: string]: any
}

interface EventHandler {
  (e: IObject): any
}

const handler: EventHandler = (e) => {
  console.log(e);
};

function handleOnClick(domEl, eventHandler: EventHandler) {
  domEl.addEventListener('click', eventHandler);
}
Enter fullscreen mode Exit fullscreen mode

What about generics?

You can make function interfaces generic just like any other interface.

interface SpecialHandler<U> {
  (event: U): any
}

const handler: SpecialHandler<string> = (eventString) => {
  document.title = eventString;
};

function registerEvent(eventName, handler: SpecialHandler) {

}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player