Open In App

How to Declare an Array of Strings in TypeScript ?

Arrays are fundamental data structures in TypeScript, enabling developers to manage collections of elements efficiently.

Below are the approaches to declare an Array of strings in TypeScript:



Square Brackets Notation

Using square brackets notation is the most common and straightforward method to declare an array of strings in TypeScript. It involves enclosing the string type within square brackets.



Syntax:

let myArray: string[] = ["string1", "string2", "string3"];

Example: In this example, we declare an array named fruits containing three strings representing different types of fruits.




let fruits: string[] = ["Apple", "Banana", "Orange"];
console.log(fruits);

Output

["Apple", "Banana", "Orange"]

Array Constructor

Another way to declare an array of strings in TypeScript is by using the Array constructor. You can specify the type of elements the array will contain by passing it as an argument to the constructor.

Syntax:

let myArray: Array<string> = new Array<string>("string1", "string2", "string3");

Example: In this example, we use the Array constructor to create an array named colors containing different color names as strings.




let colors: Array<string> = new Array<string>("Red", "Green", "Blue");
console.log(colors);

Output

["Red", "Green", "Blue"]
Article Tags :