Harry Yates

I'm a web developer focused on TypeScript, React, and Three.js.

Callbacks in TypeScript

Wed, 28th Feb 2024

Understanding Callbacks in TypeScript

In the programming world, particularly with languages like JavaScript and TypeScript, callbacks are a fundamental concept that can initially seem complex.

However, once understood, they open up possibilities regarding asynchronous operations.

What is a Callback?

A callback is a function passed into another function as an argument. This passed-in function is then called or executed within the outer function.

The concept might sound circular or confusing at first. Still, it's a powerful way to handle operations that may not happen immediately, such as data fetching, timers, or user interactions.

Why Callbacks?

Callbacks provide a way to ensure that certain code doesn’t execute until other code has finished its execution.

This is particularly useful in scenarios where operations must occur in a specific sequence, especially in asynchronous programming, where we might wait for data from a server or user input.

A Simple TypeScript Callback Example

Suppose we have a function that calculates the product of two numbers and then does something with the result. This "doing something" part is where our callback comes into play.

First, we define our callback type. In TypeScript, we can specify what kind of functions we expect as callbacks using type aliases. For our example, we want a callback that takes a single number (our product) and doesn't return anything (void):

Post

Next, we create our calculateProduct function. It takes two numbers and a callback. After calculating the product of the two numbers, it passes the result to the callback function:

Post

Now, let's use our calculateProduct function with a callback that logs the product to the console:

Post

In this example, when calculateProduct is called with 5, 10, and a logging function as arguments, it calculates the product (50), then executes the callback, logging "The product is 50." to the console.

Understanding void in Callbacks

In our Callback type definition, we used => void to indicate that our callback function is not expected to return a value.

The focus of a callback is on the action it performs with its input, not on returning data back to the caller.

This distinction is crucial for understanding how callbacks are used to handle side effects or asynchronous operations rather than compute values for immediate use.