How to use Array Generic Type In Typescript
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.
const numbers: Array<number> = [1, 2, 3, 4];
const strings: Array<string> = ['Geeks', 'For','Geeks'];
const mixedArr: Array<number | string | boolean> =
['w3wiki', 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: ["w3wiki", 1, 2, true, "TypeScript", false]
How to Define a Generic Type for an Array in TypeScript ?
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.
Table of Content
- Using the Type Alias
- Using Array Generic Type
- Using Tuple Types