Open In App

TypeScript Optional Parameters

TypeScript Optional Parameters are used for making parameters optional. In Typescript, “?” represents optional parameters. We use optional parameters when it’s not mandatory for that parameter to have a value or to be specified. Even if a function specifies parameters, you can call it without giving any arguments in JavaScript.

Every function call in TypeScript is checked by the compiler and an error is issued when The function specifies a different number of parameters than the number of arguments or when alternatively, the kinds of arguments do not match the types of function parameters. We use the “?” after the parameter name to make a function parameter optional.



Syntax:

function f(x?: Type) {
// ...
}

Parameters:

Example 1: In this example, we will write a function add, where num1 will be the mandatory argument and num2 is the optional argument. This function return type is void. If num2 is not undefined, then it will return sum of num1 and num2.




// Function to add two numbers
function add(num1: number, num2?: number): number {
    if (typeof num2 !== "undefined") {
        return num1 + num2;
    }
    return num1;
}
 
// Function call
console.log(add(2, 3));
console.log(add(9));

Output:



5
9

Example 2: In this example, will learn about Optional Parameters in Callbacks in which callbacks takes two parameter. it will produce a random number and show results accordingly.




interface Callback {
    (result: string, error?: string): void;
}
 
function fun(callback: Callback) {
    setTimeout(() => {
        const success = Math.random() < 0.5;
        if (success) {
            callback('Operation succeeded');
        } else {
            callback('undefined', 'Operation failed');
        }
    }, 1000);
}
 
function handler(result: string, error?: string) {
    if (error) {
        console.error('Error:', error);
    } else {
        console.log('Success:', result);
    }
}
fun(handler);

Output:

Success: Operation succeeded

Note: When writing a function type for a callback, never write an optional parameter unless you intend to call the function without passing that argument.


Article Tags :