Open In App

TypeScript Optional Parameters

Last Updated : 08 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • f is the name of the function that you are defining.
  • x is the name of the parameter.
  • x? is the optional parameter,? represent the optional feature.
  • Type is the data type you want to pass as a parameter.

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.

Javascript




// 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.

Javascript




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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads