Tuesday, February 8, 2022

TypeScript part 2

Variables in TypeScript

Variables are named storage locations in memory where you can store a value and use it as part of any expression.

TypeScript is in strict Mode of JavaScript and hence declaring variables in mandatory.

Variables in typescript can be declared by using the following reasons.

a) Var

b) let  

c) const


var is used to define function scope variables so that it is accessible from any location within the function.

let is used to define block scope variable and hence it cannot be accessed outside the block.

const is used to define block scope variables which must be initialized with a value and cannot be shadowed.

shadowing is the process of using the same name identifier with different value within the scope.

Syntax


function f1()  {

    var x=10;

    (x==10)

    {

        document.write("x=" +x); //Valid

    }

}


function f2() {

    var x=10;

    if(x==10)

    {

        let y=20;   //block scope

    }

    document.write("x=" +x);   //valid

    document.write("y=" +y)   //invalid

}


Note:

Variable Naming Conventions:

Variable name must start with alphabet or underscore

It cant contain periods(" ." )

It can be alpha numeric

Variable length maximum is upto 255 characters.

Examples

// var sales2019=50000  //valid

var 2019sales=22222  //invalid

var sales.2019=234343  //invalid

var 2019sales=40000  //valid

var sales_2019  //valid


Data Types in TypeScript

a ) Primitive Data Type:

JavaScript is implicitly typed that is the data type is determined according to the value assigned.

Typescript uses a duck type mechanism where the variables are strictly typed once you define any specific type of value , it cannot handle contra dictionary type.

Primitive Types are stored in Memory Stack(LIFO).

They have fixed value.

The reference will return a value and hence they are also known as "value types"

Syntax:

var x=10;

if(x==10)

{

    x=="John"---->Invalid in typescript , but valid in javascript

}

If a value is not defined, then implicitly type script designates  "any " type which is the root type of all types in TypeScript.


1 Number-- > It can store numeric Data. It includes any of the following

    Signed Integer

    Unsigned Integer

    Floating Point

    Decimal

    Double

    Exponent

Example:



2 String--> It can store char or chars.

A string literal is combination of  group of characters enclosed in quotes.

It can be alphanumeric and special characters.

Type Script string literal can be defined with 

a double quotes  "  "

b single quotes ' '

c back tick ~  ~ 


The language standards for TypeScript (tslint) recommends to use double quotes for a string and single quote for inner string.

Syntax:

let msg:string ="outstring ('innerstring')";


The back tick is used to configure any string with typescript expression  "$ { } "

Syntax :

let msg:string =`Next Year  $ {2019 + 1 } ` 


A string representation in typescript  cannot print certain special characters . To print the non printable characters in a string , you have to use an escape sequence character   "\n".


Syntax :

let path: string =  "D:\\Image\car.jpg";

o/p  == D:\Image\car.jpg


Example





html files changes








Output:








Open in Live server






3 Booleans--> It can store True or False.

In typescript Boolean true holds 1 and false zero. However , the Boolean conditions are satisified  by using true or false not by (0 or 1).

Important: the Boolean values initialized with true or false must use the same value for Boolean condition to avoid overlapping issues.

Syntax

let a:boolean=true;

if(a==false)  //not recommended

if(a==true) // valid

The default value for boolean type  is "false". i,e if not initialize with any value then it return false.

Example




let actorid:number=1;
let Name:string ="Pawan Kalyan"
let ishero: boolean=true;
let message:string =" ";
message=(ishero==true) ? " Yes" :  "No";
console.log("actorid=" + actorid + "\n" + "name=" + Name + " \n" + "ishero=" + ishero);

output:







Null Data type

A null type is configured by using a keyword "null"

It can store only a "null value"

A null type specifies reference in memory only when it have a value.

It returns a null value if reference is not created dynamically.

Syntax : let variableName :null

Now, it will accept only null.


Undefined Type:

let uname:-- By default any in typescript

let uname-->By default undefined in javascript

It is used to specify a reference whose data type will be determined dynamically during run time.

The undefined type is returned with "undefined " value if any value is not initialized dynamically.

Syntax

let uname: undefined=undefined;  //Valid

let uname: undefined="John"   //InValid

Union Type:

 A union type enables any reference to handle various types of values.

You can create a union of Types by using "|" Pipe symbol.

Syntax

let data:string  | number | boolean 

data="John "

data= 10;

data=true;

Non Primitive Types

The non primitive types are stored in a memory heap.
They don't have any fixed value. The range of values will change according to the browser memory.
1 Array Types
2 Object Types
3 Regular Expression


1 Array Types

Array are used in computer programming to reduce over  head and complexity.

Arrays can reduce over -head by storing values in a sequential order.

Arrays can reduce complexity by storing multiple values under a single reference name.

Typescript can allow array to handle similar type of values or various types of values.

Typescript Array Size can be changed dynamically. It resembles collection which includes a stack, queues, hashtable.


Array Type is declared by using the Meta Character " [ ] "


Syntax:

let cities : string[] =["Delhi ", "Hyderabad " ]  //string array

let fruits: string[] = ['Apple', 'Orange', 'Banana'];

Using a generic array type, Array<elementType>.

let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];


let fruits: Array<string>;
fruits = ['Apple', 'Orange', 'Banana']; 

let ids: Array<number>;
ids = [23, 34, 100, 124, 44]; 

let sales : number[] = [1000,4000]   // number array

let values : any[] =  [1, " TV" , true ];  //anonymous array to store any type of values


Array memory can be allocated by using a array constructor ,which can dynamically handle values.

let cities:string [] =new Array ("Delhi ","Hyd" );

or

let cities:string[] =new Array();
cities[0]="Delhi";
cities[1]="Hyd";


Array Manipulation

Reading values from an Array

a) Reading by using loops

Example


let cities: string[] =[ "Delhi ", "Hyd", "Mumbai " ]
for(var  i=0; i<cities.length; i++ ) {
console.log(cities[i] + "\n ");
}

Output




b Reading by using Iterators

let cities: string[] =[ "Delhi ", "Hyd", "Mumbai " ]
for(var item of cities) {
console.log(item);
}

Output:



Reading by using array function


let cities: string[] =[ "Delhi ", "Hyd", "Mumbai " ]
console.log(cities.toString());

Output:






Console.log(cities.join ( "  | "));
uses specified character as delimeter

let cities: string[] =[ "Delhi ", "Hyd", "Mumbai " ]
console.log(cities.join("|"));




Adding values into an Array

1 push () : Adds as last item.
2 unshift() : Adds as a first item.
3 splice(): Adds as specified Index.

Syntax:
  

let cities: string[] =[ "Delhi ", "Hyd", "Mumbai " ]
cities.push("Goa");
console.log(cities.toString());
cities.unshift("Goa");
console.log(cities.toString());

Output:



splice is used to add and remove and item.

Syntax:
splice(StartIndex,No of Elements to Remove, ItemstoAdd);

  • StartIndex− Index at which to start changing the array.

  • No of Elements to Remove− An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.

  • element1, ..., elementN − The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.


let cities: string[] =[ "Delhi ", "Hyd", "Mumbai " ]
cities.push("Goa");
console.log(cities.toString());
cities.unshift("Goa");
console.log(cities.toString());
cities.splice(2,0,"bangalore");
console.log(cities.toString());

Output:





Remove elements from an array

Pop() : Removes and returns last element.
Shift() : Removes and returns first element.
Splice() : Removes any specific element based on index number.


Example


let cities: string[] =[ "Delhi ", "Hyd", "Mumbai " ]
cities.pop();
console.log(cities.toString());
cities.shift();
console.log(cities.toString());

Output:


Searching for an Element in an Array

indexof:
It returns the index number of specified element. If element not found it returns -1

lastIndexof
It returns the last occurence index number of the specified element. It also returns -1,
if element not found

Example

let cities: string[] =[ "Delhi ", "Hyd", "Mumbai ","Hyd" ]
let index:number=cities.indexOf("Hyd");
console.log(index);
let lastindexof:number=cities.lastIndexOf("Hyd");
if(lastindexof==-1)
{
    console.log('city not found')
}
else
{
    console.log('city found at ' + lastindexof);
}

Output:





 Sorting elements in an Array

Sort(): It arranges element in array in ascending order
reverse()" It arranges element in reverse order


let cities: string[] =[ "Delhi ", "Hyd", "Mumbai ","Goa", "Bangalore" ]
cities.sort();
console.log(cities.toString())
cities.reverse();
console.log(cities.toString())


Output














Object Type Non Primitive Type

An object in typescript refers to pseudo class.
It encapsulates a set of members which includes properties and methods.
Object Type is defined by using  { }
The data type is specified as any.

Example

object.ts
let product: any  =  {
productId:1,
productName:'Samsung',
price:  345,
qty:1
}

Regular Expression Type( Non primitive Type)

 A regular expression is used to verify the format of input value.

Regular expression is enclosed " \\ " two clash

A  value is compared with regular expression by using the method match();



[a-z]---> only lower case 
[a-z A-Z]---> both capital n small alphabets
[a,d,f]--only specified characters
[^a,d,f]--exclude specified characters



Any--> It can store any type of data. It is a default Datatype.

Void--> It can store null or undefined, It is mostly used with a method which does not return any Value.

Tuple--> It is a collection of Dissimilar Data

        Example: 

                    EmpInfo:[string, number];    --->Tuple

                    EmpInfo=["Dell",50000]

6 Enumb : It is used to create a type with collection of Constant

Syntax:

                Enum <typeName> {Const1=value1, .........};

Default Value will Start with 0. 

Note: Typescript is providing let, var, const keyword to declare the variables.

syntax:
    let|var|const <varname>:<datatype>=value;

Example:



Output



 Note: Developer can set Enum Constant Value Explicitly.

enum colours {black=100,blue=200,green };

let color:colors=colors.green; 

let colorname:string=colors[201]-->Output:green


Variable declaration without datatype and initialization will be applied with default datatype[any]

Example:

let a=100;  //number

     a="xyz";  //not accepted , reason is it is already applied with number data type.

let a;   //any datatype

a=100    //accepted

a="xyz"  //accepted



Destructuring:  

Assigning Array elements to normal variables in a simplified way is called as "Destructuring"

This is supported with TypeScript and ES6

cities array--->  ["hyd","bang","chennai","noida"]

var city1=cities[0];
var city2=cities[1]  ====== >Normal Approach

var[city1,city2]=cities;    ====>Destructuring [-Simplified compared to normal Approach]

var cities:string[]=["hyd","bang","chennai","noida"];
var[city1,city2]=cities;
console.log(city1,city2);
var[city1,,city3]=cities; //it will skip 2nd element
console.log(city1,city3);
var[city1,...others]=cities;
console.log(city1,others);



Mutable vs Immutable

Mutable means original copy will be changed.


var cities:string[]=["hyd","bang","chennai","noida"];
var[city1,city2]=cities;
console.log(city1,city2);
var[city1,,city3]=cities; //it will skip 2nd element
console.log(city1,city3);
var[city1,...others]=cities;
console.log(city1,others);

let cities1=cities;
cities1[0]="hyderabad";
console.log(cities[0]);//hyderabad

Immutable means original copy will not be changed, array (or) object can be made immutable using spread operator[....]


var cities:string[]=["hyd","bang","chennai","noida"];
var[city1,city2]=cities;
console.log(city1,city2);
var[city1,,city3]=cities; //it will skip 2nd element
console.log(city1,city3);
var[city1,...others]=cities;
console.log(city1,others);

let cities1=cities;
console.log(cities[0]);
cities1[0]="hyderabad";
console.log(cities[0]);//hyderabad

let cities2=[...cities];
console.log(cities2[0]);
cities2[0]="hyd1";
console.log(cities[0]);//hyd


Output:



Note:

Template String

let employeeName:string = "Uday"; 
let employeeDept:string = "IT"; 

// Pre-ES6 
let employeeDesc1: string = employeeName + " works in the " + employeeDept + " department."; 

// Post-ES6 
let employeeDesc2: string = `${employeeName} works in the ${employeeDept} department.`; 

console.log(employeeDesc1);//Uday works in the IT department. 
console.log(employeeDesc2);  

No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...