Lesson 28 of 60 – Callback Functions
47%

Callback Functions in TypeScript

A callback function is a function that is passed as an argument to another function. The receiving function can execute the callback when it needs it.

Note: Callback functions are very common in TypeScript, JavaScript, React, and React Native. They are frequently used for events, array methods, API operations, and reusable functions.

1. What is a Callback Function?

A callback function is a function passed to another function as an argument.

function greet(
    callback: () => void
): void {

    callback();
}

function message(): void {

    console.log("Hello");

}

greet(message);

Here, message is passed to greet() as a callback.

2. Why Use Callback Functions?

Callback functions allow us to create flexible and reusable functions.

  • Execute custom code inside another function.
  • Handle events.
  • Process arrays.
  • Handle asynchronous operations.
  • Create reusable utility functions.

3. Basic Callback Syntax

A callback can be declared as a function parameter.

function process(
    callback: () => void
): void {

    callback();
}

The type () => void means that the callback takes no parameters and does not return a value.

4. Passing a Function as a Callback

A named function can be passed as a callback.

function showMessage(): void {

    console.log("Welcome");

}

function execute(
    callback: () => void
): void {

    callback();
}

execute(showMessage);

5. Passing an Arrow Function as a Callback

Arrow functions are commonly used as callbacks.

function execute(
    callback: () => void
): void {

    callback();
}

execute(() => {

    console.log("Hello TypeScript");

});

6. Callback with a Parameter

A callback can receive parameters.

function processName(
    name: string,
    callback: (value: string) => void
): void {

    callback(name);
}

processName(
    "Amit",
    value => {

        console.log(
            "Hello " + value
        );

    }
);

7. Callback with a Number

A callback can receive a number from the calling function.

function processNumber(
    number: number,
    callback: (value: number) => void
): void {

    callback(number);
}

processNumber(
    10,
    value => {

        console.log(
            value * 2
        );

    }
);

Output:

20

8. Callback that Returns a Value

A callback can also return a value.

function calculate(
    number: number,
    callback: (value: number) => number
): number {

    return callback(number);
}

const result = calculate(
    10,
    value => value * 2
);

console.log(result);

Output:

20

9. Callback with Two Parameters

A callback can receive more than one parameter.

function calculate(
    a: number,
    b: number,
    callback: (
        x: number,
        y: number
    ) => number
): number {

    return callback(a, b);
}

console.log(
    calculate(
        10,
        20,
        (x, y) => x + y
    )
);

10. Callback Function with Type Alias

A type alias can make callback types easier to reuse.

type Calculator = (
    a: number,
    b: number
) => number;

function calculate(
    a: number,
    b: number,
    operation: Calculator
): number {

    return operation(a, b);
}

11. Addition Callback

We can pass an addition function as a callback.

type Operation = (
    a: number,
    b: number
) => number;

function calculate(
    a: number,
    b: number,
    operation: Operation
): number {

    return operation(a, b);
}

const add: Operation = (
    a,
    b
) => a + b;

console.log(
    calculate(10, 20, add)
);

12. Multiplication Callback

The same function can accept a multiplication callback.

type Operation = (
    a: number,
    b: number
) => number;

const multiply: Operation = (
    a,
    b
) => a * b;

console.log(
    calculate(
        10,
        20,
        multiply
    )
);

13. Callback with forEach()

The forEach() array method accepts a callback.

const numbers: number[] = [
    10,
    20,
    30
];

numbers.forEach(
    number => {

        console.log(number);

    }
);

The arrow function is the callback.

14. Callback with map()

The map() method uses a callback to transform every array element.

const numbers: number[] = [
    1,
    2,
    3
];

const doubled = numbers.map(
    number => number * 2
);

console.log(doubled);

Output:

[2, 4, 6]

15. Callback with filter()

The filter() method uses a callback to decide which elements should remain in the array.

const numbers: number[] = [
    10,
    15,
    20,
    25
];

const result = numbers.filter(
    number => number > 15
);

console.log(result);

Output:

[20, 25]

16. Callback with reduce()

The reduce() method uses a callback to combine array values into one result.

const numbers: number[] = [
    10,
    20,
    30
];

const total = numbers.reduce(
    (sum, number) =>
        sum + number,
    0
);

console.log(total);

Output:

60

17. Callback with setTimeout()

A callback can be executed later using setTimeout().

setTimeout(
    () => {

        console.log(
            "Hello after 2 seconds"
        );

    },
    2000
);

The arrow function is passed as a callback.

18. Callback with String Processing

A callback can process a string supplied by another function.

function processText(
    text: string,
    callback: (value: string) => string
): string {

    return callback(text);
}

const result = processText(
    "hello",
    value => value.toUpperCase()
);

console.log(result);

Output:

HELLO

19. Callback with Student Marks

Callback functions can be used to process student marks.

function processMarks(
    marks: number[],
    callback: (mark: number) => number
): number[] {

    return marks.map(
        mark => callback(mark)
    );
}

const marks = [
    50,
    60,
    70
];

const updatedMarks =
    processMarks(
        marks,
        mark => mark + 5
    );

console.log(updatedMarks);

Output:

[55, 65, 75]

20. Callback with Object

A callback can receive an object.

type Student = {
    name: string;
    marks: number;
};

function showStudent(
    student: Student,
    callback: (value: Student) => void
): void {

    callback(student);
}

showStudent(
    {
        name: "Amit",
        marks: 85
    },
    student => {

        console.log(
            student.name
        );

    }
);

21. Callback with Optional Data

A callback can receive an optional value.

function greet(
    name: string | undefined,
    callback: (
        value?: string
    ) => void
): void {

    callback(name);
}

greet(
    undefined,
    value => {

        console.log(
            value ?? "Guest"
        );

    }
);

22. Callback Functions in React

React components commonly receive callback functions through props.

type ButtonProps = {
    onClick: () => void;
};

function MyButton(
    props: ButtonProps
) {

    return (
        <button onClick={props.onClick}>
            Click
        </button>
    );
}

The onClick prop is a callback function.

23. Callback Functions in React Native

React Native components frequently use callback functions for user interactions.

type ButtonProps = {
    onPress: () => void;
};

function handlePress(): void {

    console.log(
        "Button Pressed"
    );
}

The handlePress function can be passed to a React Native button's onPress property.

24. Callback with Event Data

Event handlers can receive event information through callback functions.

type ChangeHandler = (
    value: string
) => void;

const handleChange: ChangeHandler = (
    value
) => {

    console.log(
        "Value: " + value
    );

};

This pattern is useful when creating reusable form components.

25. Callback with Multiple Arguments

A callback can receive multiple arguments.

function calculate(
    a: number,
    b: number,
    callback: (
        x: number,
        y: number
    ) => void
): void {

    callback(a, b);
}

calculate(
    10,
    20,
    (x, y) => {

        console.log(
            "Total: " + (x + y)
        );

    }
);

26. Callback with Rest Parameters

A callback can also accept a variable number of arguments.

type NumberCallback = (
    ...numbers: number[]
) => number;

const total: NumberCallback = (
    ...numbers
) => {

    return numbers.reduce(
        (sum, number) =>
            sum + number,
        0
    );
};

console.log(
    total(10, 20, 30)
);

27. Common Callback Mistake

A common mistake is calling the function immediately instead of passing the function itself.

function execute(
    callback: () => void
): void {

    callback();
}

function showMessage(): void {

    console.log("Hello");

}

// Correct
execute(showMessage);

// Also possible
execute(() => showMessage());

When passing a callback by name, use showMessage, not showMessage().

28. When to Use Callback Functions

Callback functions are useful when:

  • A function needs to execute custom code.
  • You need to process array elements.
  • You are handling user events.
  • You are creating reusable components.
  • You need delayed or asynchronous operations.
  • You want to pass behavior into another function.

29. Complete Practical Example

This example uses a callback to calculate a student's result.

type ResultCallback = (
    total: number,
    average: number
) => void;

function calculateResult(
    marks: number[],
    callback: ResultCallback
): void {

    const total = marks.reduce(
        (sum, mark) =>
            sum + mark,
        0
    );

    const average =
        total / marks.length;

    callback(
        total,
        average
    );
}

calculateResult(
    [80, 75, 90, 85],
    (total, average) => {

        console.log(
            "Total: " + total
        );

        console.log(
            "Average: " + average
        );

    }
);

Output:

Total: 330
Average: 82.5

30. Callback Functions Summary

A callback function is a function passed to another function so that it can be executed when required.

function execute(
    callback: () => void
): void {

    callback();
}

execute(() => {

    console.log("Done");

});

TypeScript function types make callback functions safer by defining their parameters and return values.

📌 Key Points

  • A callback is a function passed to another function.
  • Callbacks can receive parameters.
  • Callbacks can return values.
  • Function types describe callback parameters and return types.
  • Arrow functions are commonly used as callbacks.
  • forEach(), map(), filter(), and reduce() use callbacks.
  • Callbacks are useful for event handling.
  • React components commonly use callback props.
  • React Native uses callbacks for events such as button presses.
  • TypeScript helps ensure callbacks receive and return the expected types.

🧠 Quick Quiz

Question: What is a callback function?