0
0
Typescriptprogramming~5 mins

Generic array syntax in Typescript

Choose your learning style9 modes available
Introduction

Generic array syntax helps you create arrays that can hold any type of data safely. It makes your code flexible and type-safe.

When you want an array that can store numbers, strings, or any type without losing type information.
When writing functions that work with arrays of different types and you want to keep type safety.
When creating reusable components or data structures that handle arrays of various types.
When you want to avoid errors by ensuring all items in an array are of the same type.
Syntax
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.

Examples
An array of numbers using generic syntax.
Typescript
let numbers: Array<number> = [1, 2, 3];
An array of strings using shorthand syntax.
Typescript
let strings: string[] = ['apple', 'banana', 'cherry'];
An empty array that will hold boolean values later.
Typescript
let emptyArray: Array<boolean> = [];
An array that can hold numbers or strings using a union type.
Typescript
let mixed: Array<number | string> = [1, 'two', 3];
Sample Program

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.

Typescript
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);
OutputSuccess
Important Notes

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.

Summary

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.