Borislav Hadzhiev
Tue Mar 01 2022·2 min read
Photo by Lê Tân
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.
// ✅ 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.
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.
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.
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.
any[]
.Having the array typed as any[]
effectively turns off any type checking, so
it's not what we want most of the time.