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.
Syntax:
function functionName({ propertyName1, propertyName2 }: { propertyName1: type1, propertyName2: type2 }) {
// Function body
}
Example: A function `printUser` logs the name and age of a user object, defined with name “Alice” and age 25, passed to it.
function printUser({ name, age }
: { name: string, age: number }) {
console.log(`Name: ${name}, Age: ${age}`);
}
const user =
{
name: "Alice",
age: 25
};
printUser(user);
Output:
[LOG]: "Name: Alice, Age: 25"
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