TypeScript Optional Parameters in Callbacks
In TypeScript, optional parameters in callbacks are parameters that may or may not be provided when the callback function is invoked. They are denoted by a ? after the parameter name, allowing for more flexible function calls without requiring all arguments.
Syntax
type MyCallback = (param1: string, param2?: number) => void;
function processCallback(callback: MyCallback, param1: string, param2?: number) {
callback(param1, param2);
}
Where-
- MyCallback is a type representing a callback function with a required param1 (string) and an optional param2 (number).
- processCallback is a function that accepts a callback of type MyCallback and optional parameters param1 (string) and param2 (number). It calls the callback function with the provided parameters.
Example 1: In this example, MyCallback defines an optional parameter num. The callback function logs the string and conditionally logs the number if provided. It's called with and without the number.
type MyCallback = (param1: string, param2?: number) => void;
const myFunction: MyCallback = (str, num) => {
console.log(`Received: ${str}`);
if (num !== undefined) {
console.log(`Number: ${num}`);
} else {
console.log("Number is not provided.");
}
};
// Calling the callback with and without the optional parameter
myFunction("GeeksforGeeks");
myFunction("A Computer Science Portal", 99);
Output:
Received: GeeksforGeeks
Number is not provided.
Received: A Computer Science Portal
Number: 99
Example 2: In this example, MathOperationCallback defines a callback for math operations on two numbers with an optional description. The performMathOperation function uses this callback, accepting two numbers and an optional description.
type MathOperationCallback = (a: number, b: number, description?: string) => number;
// Function to perform math operation
function performMathOperation(
operation: MathOperationCallback,
a: number,
b: number,
description?: string
) {
const result = operation(a, b, description);
console.log(`Operation: ${description || "Unnamed"}`);
console.log(`Result: ${result}`);
}
// Custom addition function
const customAddition: MathOperationCallback = (x, y, description) => {
const sum = x + y;
return sum;
};
// Perform operations
performMathOperation(customAddition, 5, 3); // No description
performMathOperation(customAddition, 10, 7, "Adding Numbers"); // With description
Output:
Operation: Unnamed
Result: 8
Operation: Adding Numbers
Result: 17