Ways to initialize an empty String Array in TypeScript
We have several ways to initialize an empty string array in TypeScript, you can either initialize it explicitly using the
string keyword followed by a pair of square brackets, or you can use the type assertion to convert from
any array type to a
string array type.
Method 1: declare explicitly
This is a popular declaration that is highly recommended and easy to understand. First, you will use the
const keyword with the array name and then a colon. You declare the string data type followed by square brackets. Then you use the assignment to assign to an empty array by using a pair of square brackets.
const nameArray: string = ;
By the above statement, you have initialized an empty String Array in TypeScript. The above example will create an empty string array to store different names that are indexed starting from 0. We can use the loop to access array data.
Method 2: use type assertion
Type assertion is a technique to help TypeScript understand the data type we want to work with. We can create an empty array of type
any first and then use type assertion to convert to the desired string type.
const nameArray =  as string;
We will pre-create an array of type
any using the
const keyword with the array name and then use assignment to assign to an empty array. Now the array will have a data type of
any, that is the type that TypeScript will ignore checking the type, so we will use type assertion to convert back to a string array.
Method 3: use the Array constructor
In this last way, we will use the
new keyword along with the constructor of the Array object. We put the string data type inside the
const nameArray = new Array();
Through this article, we have understood the ways how to initialize an empty String Array in TypeScript in some common ways that are simple but effective in terms of readability. Hope this article was useful to you and will help you to write code faster. Thanks for reading.
Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).