Saturday, October 27, 2018

TypeScript - DataTypes - Arrays

Arrays are a bit more advanced types. Consider the following TypeScript code in a file arraysFile.ts

let myGames = ["cricket","football"];
console.log("myGames[0] = "+myGames[0]);


Compiling the file: 
$ tsc arraysFile.ts

This will create a corresponding JavaScript:

$ ls -l arraysFile.*
-rw-r--r-- 1 ubuntu ubuntu 82 Oct 27 16:21 arraysFile.js
-rw-rw-r-- 1 ubuntu ubuntu 78 Oct 27 16:21 arraysFile.ts

We will include it corresponding JavaScript in our index.html as follows:
<script src="./arraysFile.js"> </script>


Now on opening the browser we can find - in the console:
myGames[0] = cricket

Of course, this is not eye-catching.  Now let us check what DataType does this myGames variable have:
console.log("typeof(myGames) = "+typeof(myGames));

Now, if we compile our code and check the output in browser Console:
typeof(myGames) = object

We see it is of object type. This is not eye-catching either. This is because an array is of type - object.  Now, let us try to assign number to myGames array variable.
myGames = [100];

Now let us compile:

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

4 myGames = [100];
             ~~~



We have received this error that array of type number is not assignable to array of type string. Now, this is eye-catching if we think it in terms of JavaScript. But, since, this is TypeScript code - it is tobe expected. TypeScript has inferred the types of variables automatically. Since, we have initialized the variable myGames to an array of string, hence, TypeScript thinks that myGames should only be an array of type string.  So, if we assign it to an array of numbers - we therefore get an error. Now, if we change this to type string.
myGames = ["100"];

We are able to recompile it without any issues:
$ tsc arraysFile.ts
$

We can override this type checking by asssigning the myGames variable to be of type any array.

let myGames: any[] = ["cricket","football"];
console.log("myGames[0] = "+myGames[0]);
console.log("typeof(myGames) = "+typeof(myGames));
myGames = [100];
console.log("myGames == "+myGames);


Now, we are able to compile this file without any issues.

tsc arraysFile.ts
$

This is because, now I am overwriting the type of array which the TypeScript infers. But, it still have to be an array though. If I set the myGames to only 100.

myGames = 100;

On compiling, I receive the following error:

$ tsc arraysFile.ts
arraysFile.ts:6:1 - error TS2322: Type '100' is not assignable to type 'any[]'.

6 myGames = 100;
  ~~~~~~~



This is because, TypeScript is still expecting myGames variable to be of type array as we have square brackets after the keyword any[].
let myGames: any[] = ["cricket","football"];


No comments:

Post a Comment