Thursday, October 11, 2018

TypeScript - Basics of Types

The language - TypeScript has received name because of its feature: Types.

The questions which come up next are:
  • Which types are available?
  • What are the benefits of using types?
  • How can we use these types provided?
  • Since types are available in JavaScript itself, then why do we need TypeScript?
Let us answer the last question first - why do we need TypeScript? The main difference is JavaScript is dynamic typed language. Whereas, TypeScript is static typed.

Example:

String Error Test:
Say, I create a file myName.ts with the following lines:

let myName = "Sashank";
myName = 34;
console.log(myName);

Now, if I try to compile the file. The compiler throws me the following error:
$ tsc myName.ts
myName.ts:2:1 - error TS2322: Type '34' is not assignable to type 'string'.

2 myName = 34;
  ~~~~~~
Numeric Error Test:
Now, let us consider the case where we create a numeric datatype and assign a string to it.

let varAge = 34;
varAge = "Sashank";
console.log(varAge);

$ tsc varAge.ts
varAge.ts:2:1 - error TS2322: Type '"Sashank"' is not assignable to type 'number'.

2 varAge = "Sashank";
  ~~~~~~



Boolean error Test:
Let us consider the boolean type in JavaScript. A boolean variable can hold a true or a false. Let us create a file hasFood.ts

let hasFood = true;
hasFood = "true";
console.log(hasFood);

Now, if I try to compile - a error is returned.

$ tsc hasFood.ts
hasFood.ts:2:1 - error TS2322: Type '"true"' is not assignable to type 'boolean'.

2 hasFood = "true";
  ~~~~~~~


This error has happened because, we tried to assign a string value to a Boolean variable.

Any Type - no error:

Consider our file myAnyType.ts. Now, if I do not assign to the variable at declaration time. Then, we can assign any type of value to this variable because TypeScript creates the variable of type Any. This is a special type of variable.

let myAnyType;
myAnyType = "london";
myAnyType = 34
myAnyType = true;
console.log(myAnyType);

Hence, on compilation, there is no error received:

$ tsc myAnyType.ts
$

This is the same behavior as we experience in JavaScript. So, this is not utilizing the power of TypeScript. We can assign a type to the declared variable without assigning it a value.

let myAnyType:number;
myAnyType = "london";
myAnyType = 34
myAnyType = true;
console.log(myAnyType);

Now, we will receive an error at the time of compilation as follows:

$ tsc myAnyType.ts
myAnyType.ts:2:1 - error TS2322: Type '"london"' is not assignable to type 'number'.

2 myAnyType = "london";
  ~~~~~~~~~

myAnyType.ts:4:1 - error TS2322: Type 'true' is not assignable to type 'number'.

4 myAnyType = true;
  ~~~~~~~~~



This is the explicit way of assigning value to a TypeScript variable. With this, we have answered all the questions we had asked at the beginning of our post.

Reference:

No comments:

Post a Comment