DEV Community

Antonin J. (they/them)
Antonin J. (they/them)

Posted on • Updated on

How To Describe A Function Typing Using An Interface In TypeScript

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

Top comments (4)

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

You can also add JsDoc style comments (via /** style comments) in the interface so the consumer gets that documentation in the IntelliSense output. Great stuff! I enjoyed your article.

Collapse
 
antjanus profile image
Antonin J. (they/them)

NICE! I actually didn't know that!

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Great. Yea, as you can probably tell by the wacky titles of my articles (“Communicating Your Needs: TypeScript’s Value From A Buddhist Perspective”) I’m very passionate about using TypeScript to document the code in easy, meaningful ways. :)

Thread Thread
 
antjanus profile image
Antonin J. (they/them)

I'll go read it!