How to use Generics In Typescript

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" 

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

Similar Reads

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

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

Using Object Destructuring

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

Contact Us