Open In App

How to get Function Parameters from Keys in an Array of Objects Using TypeScript ?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using Generics

In this approach, we are using TypeScript Generics to create a function (approach1Fn) that accepts a type parameter T representing the keys of the objects in the data array. The function then takes a specific key as an argument, accesses the corresponding property of the first object in the array, and prints the key-value pair.

Syntax:

function functionName<T>(param: T): T {
// function body
return param;
}
const result: number = functionName<number>(42);

Example: The below example uses Generics to get Function Parameters from Keys in an Array of Objects Using TypeScript.

Javascript




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"
    },
];
function approach1Fn<T extends keyof typeof data[0]>(key: T): void {
    const data1 = data[0];
    const paraValue = data1[key];
    console.log(`${key}: ${paraValue}`);
}
approach1Fn("author");


Output:

"author: GFG User 1" 

Using Type Assertion

In this approach, we are using Type Assertion with the keyword to inform TypeScript that the key being accessed (article[key]) is indeed a valid property of the object. The key of typeof article makes sure of type safety by limiting the key to those existing in the type of the individual objects within the data array.

Syntax:

const res = data[key as keyof typeof data]; 

Example: The below example uses Type Assertion to get Function Parameters from Keys in an Array of Objects Using TypeScript.

Javascript




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"
    },
];
function approach2Fn(key: string): void {
    data.forEach((article) => {
        const paraValue = article[key as keyof typeof article];
        console.log(`${key}: ${paraValue}`);
    });
}
approach2Fn("title");


Output:

"title: Introduction to TypeScript" 
"title: Advanced JavaScript Concepts"
"title: Data Structures in C++"


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads