TypeScript, like modern JavaScript versions (ES6/ECMAScript 2015), supports default parameters in functions. Default parameter values are assigned to a function’s formal parameters when the function is called without providing specific arguments for those parameters. This can help you write more flexible and concise functions, as well as make your code more readable.
Here’s a brief syntax overview of assigning default values to parameters in TypeScript:
function functionName(parameterName: type = defaultValue): returnType {
// function body
}
You can assign default values to any number of parameters within a function. Let’s look at an example function with default parameter values:
function greet(name: string, greeting: string = 'Hello'): string {
return `${greeting}, ${name}!`;
}
In this example, the function ‘greet‘ takes two parameters: ‘name‘ and ‘greeting‘. If the ‘greeting‘ parameter is not provided when calling the function, it will default to the string ‘’Hello’‘.
Let’s see how this works with different function calls:
console.log(greet('Alice')); // "Hello, Alice!"
console.log(greet('Bob', 'Hi')); // "Hi, Bob!"
When calling ‘greet(’Alice’)‘, no ‘greeting‘ argument is provided, so the default ‘greeting‘ value ‘’Hello’‘ is used in the function body. The output of ‘greet(’Bob’, ’Hi’)‘ is ‘’Hi, Bob!’‘, as the ‘greeting‘ argument ‘’Hi’‘ is used instead of the default value.
Here’s a summary of how default parameters work in TypeScript:
Default parameters in TypeScript:
Default values are assigned to function parameters when the function is called without providing specific arguments for those parameters.
The syntax to specify a default parameter is:
parameterName: type = defaultValue.You can assign default values to any number of parameters within a function.
If a default value is specified for a parameter, it will be used in the function body when that parameter is not explicitly passed during a function call.