Saturday, October 27, 2018

TypeScript - DataTypes - Tuples

In the array world, we have a new type in TypeScript which is not available in JavaScript - Tuples. Tuples are arrays with fixed items in it. The values in tuples can be of different types. Tuples are a heterogeneous collection of values.

Let us say I want to store the count of Item which I wish to get for my Birthday.
let myBirthdayItem = ["Vada Pav", 99];

Now, if I am certain that this array will always have this format. That is, first item is a string and the second item is a number. Then I can inform TypeScript about this:
let myBirthdayItem: [string,number] = ["Vada Pav", 99];

I can specify it like this. But, now, if I reverse the order of the values.
let myBirthdayItem: [string,number] = [99,"Vada Pav"];

and on compiling, I receive the following error:

$ tsc arraysFile.ts
arraysFile.ts:8:40 - error TS2322: Type 'number' is not assignable to type 'string'.

8 let myBirthdayItem: [string,number] = [99,"Vada Pav"];
                                         ~~

arraysFile.ts:8:43 - error TS2322: Type 'string' is not assignable to type 'number'.

8 let myBirthdayItem: [string,number] = [99,"Vada Pav"];
                                            ~~~~~~~~~~

... this is because in a Tuple - order is important. The tuple has to have exactly the same format. 

To correct this issue, we must revert the order.



Reference:



Practice at:



No comments:

Post a Comment