In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.
There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.
TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type.
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);
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
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
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With