Open In App

How to Declare Parameters with Default Values in TypeScript ?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The parameters can be assigned with a default value at the time of declaring a function. You can simply give an initial value to the parameter which you want to make default. So that, if someone does not pass any value for that parameter it considers that initial value and executes the code without any errors. In TypeScript, while declaring the function and the default parameters make sure that you explicitly type all of them i.e. the parameters and the return type of the function.

Syntax:

function functionName(param1: type1, param2: type2 = initialValue): 
returnTypeOfFunction{
// Function Statements
}

Example: The below code will explain how you can declare parameters with default values in TypeScript.

Javascript




function product(num1: number, num2: number = 5):
    number {
    return num1 * num2;
}
 
const passingValueForDefaultParam =
    product(5, 3);
console.log(passingValueForDefaultParam);
const notPassingValueForDefaultParam =
    product(20);
console.log(notPassingValueForDefaultParam);


Output:

15
100

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads