0
0
Typescriptprogramming~5 mins

Callback function types in Typescript

Choose your learning style9 modes available
Introduction

Callback function types help us tell TypeScript what kind of function we expect to use later. This keeps our code safe and clear.

When you want to run a function after another function finishes.
When you pass a function as an argument to another function.
When you want to handle events like button clicks.
When you want to customize behavior by giving a function to another function.
When you want TypeScript to check that your callback functions have the right inputs and outputs.
Syntax
Typescript
function example(callback: (param: Type) => ReturnType): void {
  // function body
}

The part (param: Type) => ReturnType describes the callback's input and output.

You can have multiple parameters in the callback by separating them with commas.

Examples
This function expects a callback that takes a string and returns nothing.
Typescript
function greet(callback: (name: string) => void) {
  callback('Alice');
}
This function takes two numbers and a callback that combines them and returns a number.
Typescript
function calculate(
  a: number,
  b: number,
  callback: (x: number, y: number) => number
): number {
  return callback(a, b);
}
Using a type alias for a callback that handles error and result.
Typescript
type Callback = (error: Error | null, result?: string) => void;

function fetchData(callback: Callback) {
  // simulate success
  callback(null, 'Data loaded');
}
Sample Program

This program processes each number in an array and calls the callback to print it.

Typescript
function processNumbers(
  numbers: number[],
  callback: (num: number) => void
): void {
  for (const num of numbers) {
    callback(num);
  }
}

processNumbers([1, 2, 3], (n) => {
  console.log(`Number is: ${n}`);
});
OutputSuccess
Important Notes

Always specify the types of parameters and return values in your callback to avoid mistakes.

Callbacks can be anonymous functions or named functions.

Using type aliases for callbacks can make your code cleaner and easier to read.

Summary

Callback function types describe what inputs and outputs a callback function should have.

They help TypeScript check your code and prevent errors.

You use them when passing functions as arguments to other functions.