Data types in Typescript


Data types in Typescript:
Syntax to declare a variable :  var/let varName : datatype; 
we can also assign value at the time of variable declaration.(see below examples).
We can define datatype of a variable, from below mentioned types:

Number :

// Number
let num:number;
console.log(num);// undefined
num=33;
console.log(num); //33
console.log("What if, we will try to assign any other type of value to num");
// num="sss"; // Error :Type '"sss"' is not assignable to type 'number'.
// console.log(num);

Boolean:

let isBoolean: boolean=true// isBoolean will accept only 'true' and 'false' values.
console.log(isBoolean);

String:

all java script code is valid Typescript code so, we can also use java script way to declare a variable and it works fine.(but we should not use it) .

let str="hi";// try to avoid this way of variable declaration
//let str:string ="hello";
console.log(str); // result : "hi"

Array:
//********Array****** */
let varIntArray:number[];
varIntArray=[23,73,53,43];
console.log(varIntArray);

// another way to declare array..
let varNumArray:Array<Number>;
varNumArray=[34.44,4,22,56];
console.log(varNumArray);
//below line will generate error as varNumArray will take only numbers.

// varNumArray=[7483,"894",true];
// console.log(varNumArray);

Tuple:
//== tuple==
// it's similar to array but you can have multiple datatypes with fixed position

let myTuple:[string,number];
//initialization
myTuple=["niranjan",123];

//CASE 1: if we will try to change order of datatype , we will get error, like:
    //myTuple=[23,"3432"];//error

//CASE 2: below code will not work as, I have given 3 values while myTuple will
// accept only 2 
    //myTuple=['niranjan',123,'str 3rd value'];//Error
    //but we can use push to insert more value which can be anytype from type used 
//in Tuple definition.
    myTuple.push(33);
    myTuple.push('3rd value with the help of push');

    //myTuple.push(false);//will not acceptible as bool is not in the definition of 
//Tuple.
    console.log('MyTuple : '+ myTuple);

// CASE 3: we can create tuple with multiple data types.
    let anotherTuple:[number,string,boolean,string,number];
    //* value @ particular position should be match with tuple definition(otherwise 
//you will get Error)
    anotherTuple=[123,'strvalue',true,'anotherStrVal',323];
    console.log(anotherTuple);

//CASE 4: tuple with same datatype
    let sameDTTuple:[number,number,number,number];
    sameDTTuple=[101,202,303,404]; // here we will be able to give only 4 values
    //* but we can add more values via push
    sameDTTuple.push(999);
    console.log(sameDTTuple);
    console.log(sameDTTuple.pop());// we can pop elements from Tuple.
    console.log(sameDTTuple.pop());
    console.log(sameDTTuple.pop());
    console.log(sameDTTuple); // now sameDTTuple=[101,202]; 

Enum:

Any:

Void:

Comments