Jimenemex Jimenemex - 1 year ago 176
Javascript Question

Declare an array in TypeScript

I'm having trouble either declaring or using a boolean array in Typescript, not sure which is wrong. I get an

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 initialize all the values to be false?

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

Answer Source

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();

You can access them using the index:


and you add elements using push:


When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download