0
0
Typescriptprogramming~5 mins

Array type annotation syntax in Typescript

Choose your learning style9 modes available
Introduction
We use array type annotations to tell TypeScript what kind of items an array holds. This helps catch mistakes early and makes code easier to understand.
When you want to store a list of numbers and ensure only numbers go in the array.
When you have a list of strings like names or colors and want to prevent other types from being added.
When you want to declare an empty array but specify what type of items it will hold later.
When you want to create a function that accepts an array of a specific type as input.
When you want to return an array of a certain type from a function.
Syntax
Typescript
let arrayName: type[];

// or

let arrayName: Array<type>;
You can use either the square bracket syntax (type[]) or the generic syntax (Array). Both mean the same.
Replace 'type' with the type of items the array will hold, like number, string, or a custom type.
Examples
An array holding numbers only.
Typescript
let numbers: number[] = [1, 2, 3];
An array holding strings using the generic syntax.
Typescript
let fruits: Array<string> = ['apple', 'banana'];
An empty array that will hold booleans later.
Typescript
let emptyArray: boolean[] = [];
An array that can hold numbers or strings.
Typescript
let mixed: (number | string)[] = [1, 'two', 3];
Sample Program
This program defines a function that accepts an array of strings and prints each color. It shows how to declare an array with type annotation and how TypeScript ensures only strings are added.
Typescript
function printColors(colors: string[]): void {
  for (const color of colors) {
    console.log(color);
  }
}

const favoriteColors: string[] = ['red', 'green', 'blue'];
console.log('Colors before adding:');
printColors(favoriteColors);

favoriteColors.push('yellow');
console.log('Colors after adding:');
printColors(favoriteColors);
OutputSuccess
Important Notes
Time complexity for accessing array elements is O(1), which means very fast.
Space complexity depends on the number of items stored in the array.
A common mistake is forgetting to annotate the array type, which can lead to unexpected types being added.
Use array type annotations to catch errors early and make your code easier to read and maintain.
Summary
Array type annotations tell TypeScript what kind of items an array holds.
You can use 'type[]' or 'Array<type>' syntax to declare array types.
This helps prevent mistakes and makes your code clearer.