Borislav Hadzhiev
Fri Feb 25 2022·2 min read
Photo by Averie Woodard
To declare an array of booleans in TypeScript, set the type of the array to
boolean[]
, e.g. const arr: boolean[] = []
. If you try to add a value of any
other type to the array, the type checker would show an error.
// ✅ Array of booleans with inline declaration const arr: boolean[] = [true, false, true]; // ✅ Empty array of booleans const arr2: boolean[] = []; // ✅ Using a type type BooleanArray = boolean[]; const arr3: BooleanArray = [true, false, true];
The first example shows to how declare an array of booleans with an inline type.
If you try to add a value of any other type to the array, you'd get an error.
const arr: boolean[] = [true, false, true]; // ⛔️ Error: Argument of type 'string' is not // assignable to parameter of type 'boolean'.ts(2345) arr.push('hello');
This approach is very useful when you have to initialize the array as empty. If
you don't explicitly type an empty array, TypeScript assumes its type to be
any[]
.
// 👇️ const arr: any[] const arr = [];
TypeScript has no idea what type of values we'll add to the array, so it uses
the very broad any
type.
any
type to the array, but we'd get no help from the type checker.You should always explicitly set the type of empty arrays.
const arr: boolean[] = []; // ✅ Works arr.push(true); // ⛔️ Error: Argument of type 'string' is // not assignable to parameter of type 'boolean'.ts(2345) arr.push('hello');
On the other hand, if you initialize the array with values, you can let TypeScript infer its type.
// 👇️ const arr: boolean[] const arr = [true, false, true];
You could also use a type to define an array of strings.
type BooleanArray = boolean[]; const arr3: BooleanArray = [true, false, true];
If you have an object with a property that is a boolean array, you can also use an interface.
interface Example { bools: boolean[]; } const arr3: Example = { bools: [true, true, false], };
In some cases, you might know that the array will only have N elements of specific type. You could use a tuple in this scenario.
const arr: [boolean, boolean] = [true, false];
The arr
variable we declared above is a tuple containing 2
booleans.
If you need to declare a readonly
array of booleans, use the
Readonly
utility type.
const arr: Readonly<boolean[]> = [true, false]; // ⛔️ Error: Property 'push' does not exist on // type 'readonly boolean[]'.ts(2339) arr.push(false);
We passed the boolean[]
type to the Readonly
utility type, so the array can
only be read, but cannot be changed.
There is also a more specific ReadonlyArray
utility type that achieves the
same result.
const arr: ReadonlyArray<boolean> = [true, false]; // ⛔️ Error: Property 'push' does not exist on // type 'readonly boolean[]'.ts(2339) arr.push(false);
Notice that we passed boolean
instead of boolean[]
to the ReadonlyArray
utility type.