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
}
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`
}
You can also assign types to the arguments!
interface Sum {
(arg1: number, arg2: number): number
}
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);
}
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) {
}
Top comments (4)
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.
NICE! I actually didn't know that!
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. :)
I'll go read it!