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

JavaScript
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

Similar Reads

Object Destructuring

When we’re working with objects, we can destructure the object directly within the function parameters. This is useful when we want to extract specific properties from the object....

Array Destructuring

If one function receives an array as a parameter, we can destructure the array directly within the function parameters. This allows us to extract specific elements from the array....

Rest Parameters

Rest parameters in TypeScript allow functions to accept an indefinite number of arguments as an array. Think of them like a catch-all bucket for any extra arguments we might pass to a function. Instead of specifying every possible argument individually, we can use the rest parameter syntax, which is represented by three dots (…) followed by the name of the parameter. This lets you gather up any remaining arguments into an array, making your function more flexible and capable of handling varying numbers of inputs....

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