Arrays and Tuples in TypeScript

Similar to other languages TypeScript also has arrays to store similar data types together.
Below is the example of primitive data type array.

var a : number[];
var b : boolean[];
var c : String[];

a = [1,2,3];
b = [true, false, true];
c = ["Hello","World"]

c.pop();
c.push("TypeScrpt")

Here pop() and push() are methods applicable on array in javascript

Tuples

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];
demoTuple = [1,true];
demoTuple = [2,false];
//demoTuple = [1]; Error required in type '[number, boolean]'

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.

Leave a Comment