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