Backbencher.dev

Define Callback Function Type in TypeScript

Last updated on 21 Jan, 2023

Functions accept callback function as argument. Using TypeScript we can define the type of that function.

Here is a function that accepts another function as callback:

function parent(callback) {
  //....
  callback(message, statusCode);
}

As shown in above code, our assumption is that, message is a string and statusCode is a number. So our callback function accepts a string and a number and returns nothing.

Here is how we can define the type using TypeScript:

function parent(callback: (a: number, b: string) => void) {
  //...
}
--- ○ ---
Joby Joseph
Web Architect