Generic array syntax helps you create arrays that can hold any type of data safely. It makes your code flexible and type-safe.
Generic array syntax in Typescript
let arrayName: Array<Type> = [value1, value2, ...]; // or using shorthand let arrayName: Type[] = [value1, value2, ...];
Array<Type> and Type[] mean the same thing in TypeScript.
Use the generic form Array<Type> when you want to be explicit, and Type[] for shorter syntax.
let numbers: Array<number> = [1, 2, 3];
let strings: string[] = ['apple', 'banana', 'cherry'];
let emptyArray: Array<boolean> = [];
let mixed: Array<number | string> = [1, 'two', 3];
This program defines a generic function that prints all items in an array. It works with arrays of numbers and strings, showing how generic array syntax keeps type safety and flexibility.
function printArrayItems<T>(items: Array<T>): void { for (const item of items) { console.log(item); } } const numberArray: Array<number> = [10, 20, 30]; const stringArray: string[] = ['hello', 'world']; console.log('Number array items:'); printArrayItems(numberArray); console.log('String array items:'); printArrayItems(stringArray);
Using generic arrays keeps your code safe by checking types at compile time.
Time complexity for accessing array items is O(1).
Common mistake: mixing types in arrays without using union types can cause errors.
Use generic arrays when you want reusable code that works with any data type.
Generic array syntax lets you create arrays that hold any type safely.
You can write Array<Type> or Type[] to declare arrays.
It helps make your code flexible and prevents type errors.