Similar to other languages TypeScript also has arrays to store similar data types together.
Below is the example of primitive data type array.
let a : number[];
let b : boolean[];
let c : String[];
let mixArray: (string|number)[];
a = [1,2,3];
b = [true, false, true];
c = ["Hello","World"];
mixArray = [1,"Hello"]; //can store number or string
c.pop();
c.push("TypeScrpt")
Here pop() and push() are methods applicable on array in javascript
Tuples
- Tuples are fixed length array
- At specific position only specific data types can be stored
In JavaScript, arrays are flexible i.e we can store any data type in an array. But to do similar thing in TypeScript we have something called Tuple which is used to store fixed data in it.
var demoTuple : [number,boolean] = [20,false];
demoTuple[0]=10;
demoTuple[1]=true;
//demoTuple = [1]; Error required in type '[number, boolean]'
//demoTuple[3]=true;// Fix Tuple : Type 'true' is not assignable to type 'undefined'.
In the above example we have defined a tuple that stored number and boolean, now if we store only number it gives us error saying required in type ‘[number, boolean]’
The restriction in the Tuple is you can store only set a values as defined during declaration unlike arrays where you can store n size of data in it.