How to use Object Destructuring In Typescript
In this approach, we leverage object destructuring in TypeScript to directly extract function parameters from keys in an array of objects. This method offers concise syntax and readability.
Syntax:
function approach3Fn<T extends Record<string, any>>(data: T[], key: keyof T): void {
data.forEach((item) => {
const { [key]: paraValue } = item;
console.log(`${String(key)}: ${paraValue}`);
});
}
Example:
function approach3Fn<T extends Record<string, any>>(data: T[], key: keyof T): void {
data.forEach((item) => {
const { [key]: paraValue } = item;
console.log(`${String(key)}: ${paraValue}`);
});
}
const data = [
{
title: "Introduction to TypeScript",
views: 1000,
author: "GFG User 1"
},
{
title: "Advanced JavaScript Concepts",
views: 1500,
author: "GFG User 2"
},
{
title: "Data Structures in C++",
views: 1200,
author: "GFG User 3"
},
];
approach3Fn(data, "views");
Output:
views: 1000
views: 1500
views: 1200
How to get Function Parameters from Keys in an Array of Objects Using TypeScript ?
In TypeScript, we can extract the function parameters from keys in an array of objects by going through object properties dynamically. We can use Generics and Type Assertion to get Function Parameters from Keys in an Array of Objects Using TypeScript.
Below are the possible approaches:
Table of Content
- Using Generics
- Using Type Assertion
- Using Object Destructuring
Contact Us