Open In App

How to Define a Generic Type for an Array in TypeScript ?

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

Generics in TypeScript are a way to write reusable code that can work with different types of data. When it comes to defining generic types for arrays. TypeScript provides flexible options to ensure type safety while allowing for flexibility in the types of elements stored in the array.

Using the Type Alias

The type alias can be used to define the generic type of the array and it can be used to type the array explicitly with the specified generic type.

Syntax:

type ArrayType<T>  = T[ ];

Example: The below code uses a typed alias to define a generic type for an array in TypeScript.

Javascript




type ArrayType<T> = T[];
 
const numbers: ArrayType<number> = [1, 2, 3, 4];
const strings: ArrayType<string> = ['Geeks', 'For','Geeks'];
 
const mixedArr: ArrayType<number | string | boolean> =
    ['GeeksforGeeks', 1, 2, true, "TypeScript", false];
console.log("Numbers array: ",numbers);
console.log("Strings array: ",strings);
console.log("Mixed array: ",mixedArr);


Output:

Numbers array: [1, 2, 3, 4] 
Strings array: ["Geeks", "For", "Geeks"]
Mixed array: ["GeeksforGeeks", 1, 2, true, "TypeScript", false]

Using Array Generic Type

TypeScript also provides a built-in generic type for arrays called Array<T>. You can use it directly to define arrays with a specific element type.

Syntax:

const arrayName: Array<Type>=[element1, element2, ...]

Example: The below code uses Array Generic type to define generic type for an array.

Javascript




const numbers: Array<number> = [1, 2, 3, 4];
const strings: Array<string> = ['Geeks', 'For','Geeks'];
const mixedArr: Array<number | string | boolean> =
    ['GeeksforGeeks', 1, 2, true, "TypeScript", false];
console.log("Numbers array: ",numbers);
console.log("Strings array: ",strings);
console.log("Mixed array: ",mixedArr);


Output:

Numbers array: [1, 2, 3, 4] 
Strings array: ["Geeks", "For", "Geeks"]
Mixed array: ["GeeksforGeeks", 1, 2, true, "TypeScript", false]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads