Horje
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.

TypeScript
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.

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

Output

["Red", "Green", "Blue"]



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Filter a Dictionary by Key or Value in TypeScript Filter a Dictionary by Key or Value in TypeScript
How to Create a Dropdown Menu with CSS &amp; JavaScript ? How to Create a Dropdown Menu with CSS &amp; JavaScript ?
JavaScript Program to Reverse a Linked List JavaScript Program to Reverse a Linked List
JavaScript Program to Find the Smallest Among Three Numbers JavaScript Program to Find the Smallest Among Three Numbers
How to Iterate Array of Objects in TypeScript ? How to Iterate Array of Objects in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13