Initialize an empty String Array in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 1, 2022

banner

Check out my new book

Initialize an empty String Array in TypeScript #

You can initialize an empty string array as const arr: string[] = []. The array can contain zero or more elements of type string. Trying to add an element of a different type to the array causes the type checker to throw an error.

index.ts
// ✅ First approach (better) const arr: string[] = []; // ✅ Second approach const arr2 = [] as string[];

We initialized an empty string array as string[]. The array can contain zero or more strings, but if we try an element of a different type, we'd get an error.

index.ts
const arr: string[] = []; arr.push('a'); // ✅ OK // ⛔️ Error: Argument of type 'number' is // not assignable to parameter of type 'string'.ts(2345) arr.push(1);

You can use this approach to initialize an empty array of any type.

index.ts
const numArray: number[] = []; numArray.push(1); const objArray: { name: string }[] = []; objArray.push({ name: 'Alice' }); const twoDimensionalArray: number[][] = []; twoDimensionalArray.push([1, 2, 3]);

Note that the syntax is string[] and not [string]. This is often a source of confusion, but string[] is an array of zero or more elements of type string, and [string] is a tuple with a single string element.

An alternative way to initialize an empty string array is to use a type assertion.

index.ts
const arr2 = [] as string[]; arr2.push('a'); // ✅ OK // ⛔️ Error: Argument of type 'number' is // not assignable to parameter of type 'string'.ts(2345) arr2.push(1);

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

If we declare an empty array and don't explicitly type it like we did in the previous examples, TypeScript doesn't know what type of elements we will add to the array and types it as any[].

Having the array typed as any[] effectively turns off any type checking, so it's not what we want most of the time.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.