207

I'm having trouble either declaring or using a boolean array in Typescript, not sure which is wrong. I get an undefined error. Am I supposed to use JavaScript syntax or declare a new Array object?

Which one of these is the correct way to create the array?

private columns = boolean[];
private columns = [];
private columns = new Array<boolean>();

How would I initialise all the values to be false?

How would I access the values, can I access them like, columns[i] = true;?

1
  • 1
    correct syntax is let array: boolean[]; and yes you can access it the way you are using Commented Aug 10, 2016 at 13:47

6 Answers 6

417

Here are the different ways in which you can create an array of booleans in typescript:

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]>[];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();

You can access them using the index:

console.log(arr[5]);

and you add elements using push:

arr.push(true);

When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
3
  • 6
    Is there a good reason for having so many different ways of declaring an Array? arr5 and arr6 seem particularly jarring to me. Commented Sep 27, 2017 at 8:00
  • 4
    @RaphaëlGomès It's just the way javascript is. Check out this question regarding arr5 and arr6: stackoverflow.com/questions/8205691/… Commented Sep 27, 2017 at 13:37
  • @juanjinario not really. there are two problems with it. the first is that you don't assign a real value to the variable, and so array.push(...) will end up in a runtime error. also, sine you haven't included any type for the array you'll get never[]. Commented Jun 6, 2020 at 16:05
19

this is how you can create an array of boolean in TS and initialize it with false:

var array: boolean[] = [false, false, false]

or another approach can be:

var array2: Array<boolean> =[false, false, false] 

you can specify the type after the colon which in this case is boolean array

9

Specific type of array in typescript

export class RegisterFormComponent 
{
     genders = new Array<GenderType>();   // Use any array supports different kind objects

     loadGenders()
     {
        this.genders.push({name: "Male",isoCode: 1});
        this.genders.push({name: "FeMale",isoCode: 2});
     }
}

type GenderType = { name: string, isoCode: number };    // Specified format
7

Few ways of declaring a typed array in TypeScript are

const booleans: Array<boolean> = new Array<boolean>();
// OR, JS like type and initialization
const booleans: boolean[] = [];

// or, if you have values to initialize 
const booleans: Array<boolean> = [true, false, true];
// get a vaue from that array normally
const valFalse = booleans[1];
2
let arr1: boolean[] = [];

console.log(arr1[1]);

arr1.push(true);
0

Here's my take on a implementation of a typed boolean array using the Proxy class andUint8ClampedArray as the backing storage for the booleans:

class BooleanArray
{
    #actualArray: Uint8ClampedArray;

    [index: number]: boolean;

    constructor(length? : number)
    {
        this.#actualArray = new Uint8ClampedArray(length ?? 0);
        return new Proxy(this, BooleanArray.indexedHandler);
    }

    get length(): number
    {
        return this.#actualArray.length;
    }

    private static indexedHandler: ProxyHandler<BooleanArray> =
    {
        get(target, prop)
        {
            switch (prop)
            {
                case 'length':
                    return target.length;
                default:
                    return target.#actualArray[Number(prop)] !== 0;
            }
        },
        set(target, index, value): boolean
        {
            target.#actualArray[Number(index)] = value ? 1 : 0;
            return true;
        }
    };
}

I tested it with:

var test = new BooleanArray(4);

test[1] = true;
test[3] = true;

console.log(test[0]); // Output: false
console.log(test[1]); // Output: true
console.log(test[2]); // Output: false
console.log(test[3]); // Output: true
console.log(test.length); // Output: 4
//console.log(test['str']); // Doesn't compile

Feel free to suggest improvements/fixes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.