Open In App

How to Create Arrays of Generic Interfaces in TypeScript ?

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

In TypeScript, managing data structures effectively is crucial for building robust applications. Arrays of generic interfaces provide a powerful mechanism to handle varied data types while maintaining type safety and flexibility.

There are various methods for constructing arrays of generic interfaces which are as follows:

Using Array Generics

Arrays in TypeScript support generics, enabling the creation of arrays with elements of specific types, including interfaces. This approach offers a straightforward solution for organizing and manipulating data with predefined interface structures.

Syntax:

interface MyInterface<T> {
// Define interface properties/methods using type T
}
const myArray: MyInterface<number>[] = [];

Example: Define an interface MyInterface with a generic type T, allowing for flexible data storage. The array myArray is declared with elements adhering to MyInterface<number>, ensuring each element maintains type consistency with the specified structure.

Javascript




interface MyInterface<T> {
    value: T;
}
 
const myArray: MyInterface<number>[] = [
    { value: 1 },
    { value: 2 },
    { value: 3 },
];
 
console.log(myArray);


Output

[{ value: 1 }, { value: 2 }, { value: 3 }]

Using Array Mapping

Array mapping offers a dynamic approach to transform existing arrays into arrays of generic interfaces. This method is particularly useful when dealing with data sources with diverse structures, allowing for seamless integration of interface definitions.

Syntax:

interface MyInterface {
// Define interface properties/methods
}
const myArray = existingArray.map((item: ItemType) => {
// Return transformed interface object
});

Example: In this example, we have an array existingArray containing items of type ItemType. By using array mapping, each item is transformed into a new object conforming to the interface structure defined by MyInterface, facilitating uniform data representation.

Javascript




interface MyInterface {
    id: number;
    name: string;
}
 
interface ItemType {
    id: number;
    name: string;
    description: string;
}
 
const existingArray: ItemType[] = [
    {
    id: 1,
    name: 'Item 1',
    description: 'Description 1'
    },
    {
    id: 2,
    name: 'Item 2',
    description: 'Description 2'
    },
];
 
const myArray = existingArray.map((item: ItemType) => ({
    id: item.id,
    name: item.name,
}));
 
console.log(myArray);


Output

[{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads