Default Values
TypeScript allows us to provide default values for destructured parameters. This is useful when we want to provide values if a property or element is missing.
Syntax:
function functionName(param1: Type = defaultValue1, param2: Type = defaultValue2) {
// Function body
}
Example: The`greet` function logs a greeting message, defaulting to “Bishal Paul” if no name is given. It’s called twice, first without a name and then with “w3wiki”.
function greet(name: string = "w3wiki") {
console.log(`Hello, ${name}!`);
}
greet();
greet('w3wiki');
Output:
[LOG]: "Hello, w3wiki!"
What is Parameter Destructuring in TypeScript ?
Parameter destructuring in TypeScript is a way to extract values from objects or arrays passed as function parameters, making it easier to work with their properties or elements directly within the function body.
There are several methods through which parameter destructuring is achieved in TypeScript which are as follows:
Table of Content
- Object Destructuring
- Array Destructuring
- Rest Parameters
- Default Values