How to declare an array in TypeScript



Image not found!!

In TypeScript, you can declare an array using the following syntax:

typescript
// Explicitly declare the type of elements in the array let myArray: number[] = [1, 2, 3, 4, 5]; // Another way to declare an array with the Array<elementType> syntax let anotherArray: Array<string> = ["apple", "banana", "orange"]; // You can also declare an array without initializing it let emptyArray: number[] = []; // Initialize an array later emptyArray = [1, 2, 3]; // Arrays can contain different types of elements let mixedArray: (string | number)[] = ["apple", 1, "banana", 2]; // TypeScript allows you to use the Array type with union types let unionArray: Array<string | number> = ["apple", 1, "banana", 2];

In the examples above:

  • myArray is an array of numbers.
  • anotherArray is an array of strings.
  • emptyArray is initially declared without any elements and later initialized with numbers.
  • mixedArray is an array that can hold either strings or numbers.
  • unionArray is another way to declare an array with a union type.

Remember that TypeScript provides static typing, so declaring the type of elements in the array allows the compiler to catch potential type errors during development. If you try to assign an element of the wrong type to the array, TypeScript will generate a compilation error.