How To Initialize an Empty String Array in TypeScript

In the daily programmer’s coding work, we want to initialize an empty string array to be able to perform many different functions of the job, this is very easy in JavaScript, but for TypeScript, it is a bit difficult and distinctive. So we wrote this article to show you how to do it by declaring explicitly type, type assertion and array constructor. Let’s find out together.

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 let or 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.

Example:

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.

Example:

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

Example:

const nameArray = new Array();

Summary

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.

Leave a Reply

Your email address will not be published. Required fields are marked *