Typing Callback Functions in TypeScript?

By Hemanta Sundaray on 2023-04-16

A callback function is a function that is passed as an argument to another function. This allows the function to be called or executed at a later time when it’s needed.

In TypeScript, you can use fat arrow (=>) syntax to type annotate callback functions.

Here’s an example:

// Define a type alias for the callback function
type TimeoutCallback = () => void

// Define a callback function that logs a greeting after 1 second.
const delayedGreeting: TimeoutCallback = () => {
  console.log("Hello after 1 second.")
}
// // Pass the delayedGreeting callback function as the first argument to the setTimeout function
setTimeout(delayedGreeting, 1000) // Output: Hello after 1 second.

First, we defined a type alias TimeoutCallback using TypeScript's type keyword. The TimeoutCallback type represents a function that takes no arguments and returns void, indicating that it does not return any value.

Next, we define a callback function delayedGreeting that matches the TimeoutCallback type. This function logs a greeting after 1 second.

Finally, we pass the delayedGreeting callback function as the first argument to the setTimeout function, which delays the execution of the delayedGreeting function by 1 second.

Now, if we were to accidentally pass a callback that doesn’t match the TimeoutCallback type, TypeScript would give us an error message.

Join the Newsletter