How Do Callback Functions Work in TypeScript?

Learn How Do Callback Functions Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Callback Functions in TypeScript

A callback function is a function passed as an argument to another function so that it can be executed at an appropriate point. Callbacks are widely used in JavaScript and TypeScript for event handling, array processing, sorting, timers, data transformation, and asynchronous operations.

TypeScript makes callbacks safer by allowing you to describe their parameters and return types. These definitions help the compiler identify incompatible callback implementations and incorrect arguments before the application runs.

Understanding callback functions is important when working with browser events, framework event handlers, reusable utility functions, APIs, and libraries that accept custom behavior. Well-typed callbacks improve code reuse while making function contracts easier to understand and maintain.

1. What Is a Callback Function?

A callback is a function supplied to another function as an argument. The receiving function decides when and how to invoke it. The callback may execute immediately, after a condition is satisfied, in response to an event, or after an asynchronous operation completes.

function processMessage(
  message: string,
  callback: (value: string) => void
): void {
  callback(message);
}

function displayMessage(value: string): void {
  console.log(value);
}

processMessage("Welcome to TypeScript", displayMessage);

The processMessage function receives a message and a callback. It passes the message to the callback, which displays it. The callback is not executed when its name is passed without parentheses; it is executed when callback(message) is called.

This separation lets the receiving function focus on its main responsibility while allowing the caller to decide what action should happen next.

2. Defining Callback Types

When a callback is used in multiple places, defining a named function type can make the code more readable. The type describes the parameters accepted by the callback and the result it produces.

type NumberCallback = (value: number) => void;

function processNumber(
  value: number,
  callback: NumberCallback
): void {
  callback(value);
}

const logNumber: NumberCallback = (value) => {
  console.log("Number:", value);
};

const displaySquare: NumberCallback = (value) => {
  console.log("Square:", value * value);
};

processNumber(5, logNumber);
processNumber(5, displaySquare);

The NumberCallback type defines a function that receives a number and whose return value is intended to be ignored. Both callback implementations satisfy this contract even though they perform different operations.

Named callback types are helpful when the same signature appears across services, components, configuration objects, and utility functions. They also make it easier to update a shared contract consistently as an application grows.

3. Using Arrow Functions as Callbacks

Arrow functions are commonly used as callbacks because they can be defined directly where they are needed. This is convenient when the callback contains only a few statements and does not need to be reused elsewhere.

function calculateValue(
  value: number,
  callback: (result: number) => void
): void {
  callback(value * 2);
}

calculateValue(10, (result) => {
  console.log("Calculated result:", result);
});

calculateValue(15, (result) => {
  console.log("Result plus five:", result + 5);
});

Each arrow function is passed directly to calculateValue. TypeScript infers the callback parameter as a number from the expected callback signature.

This is an example of contextual typing. Instead of manually declaring the type of result, TypeScript determines it from the position where the arrow function is used. Contextual typing reduces repetitive annotations while preserving type checking.

4. Callbacks with Multiple Parameters

A callback can receive multiple arguments when the calling function has more information to provide. You can define the required parameter types directly in the callback signature or place the signature in a reusable type alias.

type CourseCallback = (
  title: string,
  duration: number
) => void;

function processCourse(
  callback: CourseCallback
): void {
  callback("TypeScript Fundamentals", 8);
}

processCourse((title, duration) => {
  console.log("Course:", title);
  console.log("Duration:", duration, "hours");
});

The callback receives a course title and its duration. TypeScript infers the types of both callback parameters from the declared signature.

Multiple parameters are useful when a callback needs separate values, such as an item and its index, an event and its source, or a result and associated metadata. When many related values must be passed together, consider using a typed object instead of expanding the number of callback parameters.

5. Callbacks That Return Values

Not all callbacks perform side effects. Some return a value that the receiving function uses to calculate a result. In these cases, the callback's return type is an important part of the contract.

type NumberTransformer = (value: number) => number;

function transformNumber(
  value: number,
  callback: NumberTransformer
): number {
  return callback(value);
}

const double: NumberTransformer = (value) => {
  return value * 2;
};

const square: NumberTransformer = (value) => {
  return value * value;
};

console.log(transformNumber(5, double));
console.log(transformNumber(5, square));

Unlike a callback returning void, this callback returns a number that the parent function passes back to its caller. The NumberTransformer type ensures that compatible implementations return numeric results.

This approach is useful for customizable calculations, data transformations, validation results, sorting rules, and other operations where the receiving function needs the callback's output to continue its work.

6. Callback Functions with Array Methods

JavaScript array methods such as map(), filter(), and forEach() use callbacks. TypeScript provides contextual types for these callbacks based on the array's element type and the method's signature.

const scores: number[] = [45, 80, 92, 60, 35];

const doubledScores = scores.map((score) => {
  return score * 2;
});

const passingScores = scores.filter((score) => {
  return score >= 50;
});

scores.forEach((score, index) => {
  console.log("Score at index", index, ":", score);
});

console.log(doubledScores);
console.log(passingScores);

The map() callback transforms each element, while filter() keeps elements that satisfy a condition. The forEach() callback performs an action for each element without creating a transformed array.

TypeScript infers score as a number and index as a number. If the array's element type changes, the callback's contextual types update accordingly.

These methods demonstrate how callback functions make operations reusable and expressive. Instead of writing a separate loop for every task, you supply the specific behavior that should happen for each element.

7. Understanding the Difference Between Synchronous and Asynchronous Callbacks

A synchronous callback runs as part of the current operation. An asynchronous callback or callback-based API schedules work that can happen later, such as after a timer fires or a browser event occurs.

Synchronous callback

function runTask(
  callback: () => void
): void {
  console.log("Before callback");
  callback();
  console.log("After callback");
}

runTask(() => {
  console.log("Callback executed");
});

The callback runs immediately. Its output appears between the messages printed before and after it is invoked.

Asynchronous callback

function scheduleTask(
  callback: () => void
): void {
  setTimeout(callback, 1000);
}

scheduleTask(() => {
  console.log("Timer callback executed");
});

console.log("This message appears first");

The timer callback is scheduled to run later, so the final console message is printed before the timer callback under normal execution.

The callback type alone does not determine when a callback runs. Execution timing depends on the implementation of the function receiving it. Always check whether the API invokes a callback immediately, schedules it for later, or invokes it multiple times.

8. Typing Event Handler Callbacks

Event handlers are callbacks that execute when an event occurs, such as a button click, keyboard input, or form submission. Their types depend on the event system and the framework being used.

In a browser application, you can attach a typed event listener using the DOM API:

const button = document.querySelector(
  "#save-button"
);

if (button !== null) {
  button.addEventListener("click", (event) => {
    console.log("Button clicked");
    console.log(event.type);
  });
}

The generic argument to querySelector tells TypeScript that the selected element is expected to be an HTML button. The null check handles the possibility that the element is not present in the document.

The DOM API provides contextual typing for the event callback. The event parameter is inferred from the listener type, so a separate annotation is normally unnecessary.

Frameworks such as Angular and React have their own event handler contracts. Use the types provided by the framework rather than assuming every event system uses the same callback signature.

9. Optional Parameters in Callback Types

Callback types can include optional parameters when the function contract genuinely permits callers to omit those arguments. The question mark indicates that the corresponding argument may be absent.

type MessageHandler = (
  message: string,
  category?: string
) => void;

const logMessage: MessageHandler = (
  message,
  category = "INFO"
) => {
  console.log("[" + category + "] " + message);
};

logMessage("Application started");
logMessage("Request failed", "ERROR");

The callback's category parameter is optional, so the function that invokes the callback may omit it. The implementation provides a default value when category is undefined.

Do not mark a callback parameter optional simply because the callback implementation does not use it. Optionality describes what callers are allowed to supply, so the signature should reflect the real contract of the API.

10. Generic Callback Functions

Generics allow callback functions to work with multiple data types while preserving the relationship between input and output values. This is useful for reusable data processors, transformation utilities, and libraries that should work with different models.

function processValue(
  value: T,
  callback: (input: T) => TResult
): TResult {
  return callback(value);
}

const numberResult = processValue(10, (value) => {
  return value * 2;
});

const textResult = processValue("typescript", (value) => {
  return value.toUpperCase();
});

console.log(numberResult);
console.log(textResult);

The generic parameter T represents the input type, while TResult represents the callback's result type. TypeScript infers the appropriate types from the supplied value and callback implementation.

Generic callbacks are useful when a function should support different data structures without falling back to any. They preserve type information so that the result can be safely used by the rest of the application.

11. Asynchronous Callbacks and Promises

A callback can be asynchronous and return a Promise. When the receiving function needs to wait for the callback's work to finish, its signature should describe the Promise and the implementation should await it.

type AsyncTask = () => Promise;

async function executeTask(
  task: AsyncTask
): Promise {
  return await task();
}

const loadCourse: AsyncTask = async () => {
  return "TypeScript Fundamentals";
};

async function main(): Promise {
  const course = await executeTask(loadCourse);
  console.log(course);
}

void main();

The AsyncTask type describes a function that returns a Promise resolving to a value of type T. The executeTask function waits for the callback's Promise and returns its resolved result.

Calling an async callback without awaiting its Promise does not automatically make the surrounding function wait for completion. This is a common source of bugs when a process depends on asynchronous work finishing before it continues.

Promise rejections must also be handled appropriately. Use try...catch, propagate the rejection to a caller that handles it, or apply another deliberate error-handling strategy that suits the application.

12. Callback Functions for Validation

Callbacks are useful for separating reusable processing logic from the rule that determines whether a value is acceptable. A function can receive a validation callback and use its Boolean result to decide what to do.

type Validator = (value: T) => boolean;

function validateValue(
  value: T,
  validator: Validator
): boolean {
  return validator(value);
}

const isPositive: Validator = (value) => {
  return value > 0;
};

const isLongEnough: Validator = (value) => {
  return value.length >= 8;
};

console.log(validateValue(10, isPositive));
console.log(validateValue("typescript", isLongEnough));

The generic Validator type allows different validation rules to operate on different input types. The callback returns a Boolean indicating whether the value satisfies the supplied rule.

This pattern helps separate validation rules from the code that uses them. However, TypeScript callback types do not replace runtime checks for values originating from untrusted sources. Validate external data before treating it as a trusted application model.

13. Avoiding Common Callback Mistakes

Calling a callback instead of passing it

Passing handleResult supplies the function, while passing handleResult() invokes it immediately and passes its return value instead.

Using any for callback parameters

Define accurate parameter and return types so TypeScript can verify the callback implementation and its usage.

Assuming callbacks always run synchronously

A callback may execute later or multiple times, depending on the receiving API. Understand the API's timing and invocation behavior.

Ignoring Promise results

If a callback returns a Promise and the caller depends on its result, await it and account for possible rejection.

Making callback parameters optional incorrectly

An optional parameter allows the caller to omit the argument. Mark parameters optional only when the callback contract truly supports that behavior.

14. Callback Functions vs Promises

Callbacks and Promises are both used to coordinate work, but they represent different programming patterns. A callback passes a function to another function, while a Promise represents a value that may become available later or fail.

function runWithCallback(
  callback: (message: string) => void
): void {
  callback("Task completed");
}

function runWithPromise(): Promise {
  return Promise.resolve("Task completed");
}

runWithCallback((message) => {
  console.log("Callback:", message);
});

async function main(): Promise {
  const message = await runWithPromise();
  console.log("Promise:", message);
}

void main();

The callback version delegates the next action to a supplied function. The Promise version returns an object representing the eventual result, which can be consumed with await or Promise methods.

Neither pattern is universally better. Callbacks remain useful for event handlers, array operations, and APIs designed around event notification. Promises are particularly convenient for single asynchronous results and sequential workflows because they support structured chaining and async/await syntax.

Best Practices for TypeScript Callbacks

  • Define explicit callback signatures when they form part of a reusable API.
  • Use contextual typing to avoid unnecessary parameter annotations in simple callbacks.
  • Choose void or a concrete return type according to whether the caller needs the callback's result.
  • Prefer generic callback types when input and output types should remain connected.
  • Understand whether an API invokes callbacks synchronously, asynchronously, once, or multiple times.
  • Await Promise-returning callbacks when subsequent logic depends on their completion.
  • Use descriptive type aliases for callback contracts that represent important application behavior.
  • Keep callbacks focused and avoid deeply nested callback chains when a clearer alternative is available.

Conclusion

Callback functions allow TypeScript applications to separate operations from the behavior that should happen during or after those operations. Type annotations make callback contracts explicit and help catch incompatible parameters and return values during development.

Start with basic callback signatures, then apply type aliases, contextual typing, generic callbacks, event handlers, and asynchronous callback patterns as your application grows. By understanding callback timing, return values, and Promise handling, you can create flexible functions that remain predictable, reusable, and type-safe.

Code Examples

Basic Callback Function

typescript
function processMessage(
  message: string,
  callback: (value: string) => void
): void {
  callback(message);
}

function displayMessage(value: string): void {
  console.log(value);
}

processMessage("Welcome to TypeScript", displayMessage);
    

A callback is passed as a function argument and invoked by the receiving function. Its signature specifies the accepted parameter type and return behavior.

Callback with a Return Value

typescript
type NumberTransformer = (value: number) => number;

function transformNumber(
  value: number,
  callback: NumberTransformer
): number {
  return callback(value);
}

const double: NumberTransformer = value => value * 2;
const square: NumberTransformer = value => value * value;

console.log(transformNumber(5, double));
console.log(transformNumber(5, square));
    

The callback returns a numeric result that the receiving function uses and returns to its caller.

Generic Callback Function

typescript
function processValue<T, TResult>(
  value: T,
  callback: (input: T) => TResult
): TResult {
  return callback(value);
}

const numberResult = processValue(10, value => value * 2);
const textResult = processValue("typescript", value => value.toUpperCase());

console.log(numberResult);
console.log(textResult);
    

Generic callback signatures preserve input and output types, allowing the same function to process different types without using any.

Callback with Array Methods

typescript
const scores: number[] = [45, 80, 92, 60, 35];

const doubledScores = scores.map(score => score * 2);
const passingScores = scores.filter(score => score >= 50);

scores.forEach((score, index) => {
  console.log("Score at index", index, ":", score);
});

console.log(doubledScores);
console.log(passingScores);
    

Array methods accept callbacks to transform, filter, or process elements. TypeScript infers callback parameter types from the array and method signatures.

Asynchronous Callback

typescript
type AsyncTask<T> = () => Promise<T>;

async function executeTask<T>(
  task: AsyncTask<T>
): Promise<T> {
  return await task();
}

const loadCourse: AsyncTask<string> = async () => {
  return "TypeScript Fundamentals";
};

async function main(): Promise<void> {
  const course = await executeTask(loadCourse);
  console.log(course);
}

void main();
    

The callback returns a Promise, and the receiving function awaits it before returning the resolved value. This preserves the asynchronous result type.

Pro Tip

Treat a callback signature as a contract that defines what the caller must supply and what the receiving function expects. Use contextual typing for simple callbacks, reusable aliases for shared behavior, and Promise-based callback signatures when the caller must await asynchronous work.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.