How to use Mapped Types and Generics In Typescript
Mapped types allow you to create new types by transforming properties of an existing type, and generics enable you to define types that can work with various types of data. By combining these two features, you can create a generic type for arrays of objects that can be reused with different object structures.
Syntax:
type ArrayOf<T> = {
[K in keyof T]: T[K];
}[];
const array_name: ArrayOf<{ key1: type1; key2: type2; key3: type3 }> = [];
Example:
type Cricketer = {
cktr_name: string;
cktr_team: string;
cktr_runs: number;
};
type ArrayOf<T> = T[];
const myArr: ArrayOf<Cricketer> = [
{
cktr_name: "Virat Kohli",
cktr_team: "India",
cktr_runs: 26000,
},
{
cktr_name: "AB De Villiers",
cktr_team: "South Africa",
cktr_runs: 15000,
},
{
cktr_name: "David Warner",
cktr_team: "Australia",
cktr_runs: 13000,
},
];
myArr.forEach(({ cktr_name, cktr_team, cktr_runs }) => {
console.log(`Hi, I'm ${cktr_name} from ${cktr_team}, with
${cktr_runs} runs for my country.`);
});
Output:
Hi, I'm Virat Kohli from India, with 26000 runs for my country.
Hi, I'm AB De Villiers from South Africa, with 15000 runs for my country.
Hi, I'm David Warner from Australia, with 13000 runs for my country.
How can I Define an Array of Objects in TypeScript?
In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript.
There are many methods of declaring an array of objects in TypeScript as listed below:
Table of Content
- Using the inline type declaration
- Using the in-built interfaces and type
- Using the built-in Array type
- Using the typeof operator
- Using Mapped Types and Generics