Initialize an empty Boolean Array in TypeScript

avatar

Borislav Hadzhiev

Tue Mar 01 20222 min read

banner

Photo by Lê Tân

Initialize an empty Boolean Array in TypeScript #

You can initialize an empty boolean array as const arr: boolean[] = []. The array can contain zero or more elements of type boolean. 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: boolean[] = []; // ✅ Second approach const arr2 = [] as boolean[];

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

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

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

index.ts
const strArray: string[] = []; strArray.push('hello'); const objArray: { id: number }[] = []; objArray.push({ id: 1 }); const twoDimensionalArray: string[][] = []; twoDimensionalArray.push(['a', 'b', 'c']);

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

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

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

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.