TypeScript Learning
Typescript is a superset of Javascript or it is JS++ [ JavaScript ++ ] where first + = brings Type-Safety to Javascript and second+ = Makes the developer's life easy.
Type-safety
All the Typescript code is trans-compiled into Javascript code by using the Typescript compiler. During this phase, if the compiler notices any errors then it shows immediately.
Ex : var x : number = 10;
x = "Hello"; // assigning string value to integer variable. Typescript compiler throws error notices this errors then it shows immediately. In the end, The browser understands only Javascript.
Typescript is strictly typed
Ease of use
With a few lines of Typescript code, we can write a lot of Javascript code. Ex: we can create an Employee class with functions and properties with few lines of code.
We can also make use of OOP concepts like interface, inheritance, and encapsulation just like we do in c#.
It also provides us easy syntax
https://www.typescriptlang.org/play/
Node.Js --->software that will allow us to execute Javascript commands in command prompt.
NPM--->Node package manager is an command which will allow us to install any Javascript framework. This command will pull the software from online and will install it in our machine
search for npm install online and download both node.js and npm and install it. Once you install, open the command prompt and run below commands
node -v
npm -v
VARIABLES SECTION
=================
string variables can be initialized with double or backtick quotes. If we use backtick then we make of $ placeholders for variables.
string data = "<a href = ' ' /> "; ---->here i have initialized with double quotes and hence i used single quote inside anchor tag.
string data = '<a href = " " />'; ---->here i have initialized with single quotes and hence i used double quote inside anchor tag.
enum types are used to store collections/sequence of constant values.
union types---> are used to combine two different datatypes in one variables using pipe character.
var sm : string | number;
sm = "hello";
sm = 100;
any datatype-->we can store any datatype including objects
var data:any = 100;
data = "hello";
Array will start with index 0
homogeneous arrays---> we can store sequence of strings or seqeunce of numbers and so on. But we cannot store different datatypes
var data:Array<string> = ["Angular","React","Python"];
heterogeneous arrays---> we can store sequence of any different datatypes
var data:Array<any> = ["Angular",100,"Python",false,{
productID : 1,
productName : "IPhone",
price : 1000
}];
prompt -->used to take input data from user [ like a textbox in alert window ]
OPERATORS SECTION
==================
arthmetic
----------------
+=, *=,- =, /= ----->arithmetic operators used along with assignment then it is called compound assignment.
comparison
----------------
compare one variable with another variable or one value with another value we use comparsion operators. It will either return true or false
we use ==== or == to check the equality in Javascript or Typescript
!== ---->opp of equality operator
we also have < , > and <= , >=
Logical
---------
&& and || and !
! --->we can reverse the result of an entrie expression or operation
Trenary
-----------
testexpression ? value1 : value2 [ value 1 or value 2 can be an expression or also an ternary operator]
FLOW CONTROL (Used to determine the order in which our code is executed)
==================================================================
Three mainly
Selctive -->if and if else and switch in order to execute the code based on conditons
Iterative-->for loop and while loop executes the same code multiples times
Transfer-->transfer the execution of code form one part to another like return,break
OBJECTS
========
Everything in this world is object so these object representation helps us to map the real world problems to a software solution easily. Object literal syntax is nothing but key and value paris inside the flower bracket.
var product = {
id: 1001,
Name: "Headphone",
Price: 1654.56
};
To access the object, syntax is objectName.propertyName
For in loop
--------------
It is special loop mainly for objects. It sames as foreach in c#
Push ---> is a method used to add into already defined Array
var course = ["Angular","React","Python"];
course.push("Java");
course.push(10); --->This is an error becuase the typescript assumes that we have already defined course array variable of type "STRING" and hence it wont allow us to other than string types.
So to solve it, we can directly add the differernt types into array variable at the time of its declaration like shown below
var course = ["Angular","React","Python",10];---->Now typescript assumes this array as of "ANY" type
course.push("Java");
course.push(20);
or we can also declare like this
var course : any = ["Angular","React","Python",10];---->this is now heterogeneous array
course.push("Java");
course.push(20);
Array-Destructuring
----------------------------
we can take the values from the array and assign them into individual variables.
ex: var course : any = ["Angular","React","Python",10];
var[a,b,c] = courses;
Object-Destructuring
----------------------------
we can take the values from the object and assign them into individual variables.
ex: var product = {
id: 1001,
Name: "Headphone",
Price: 1654.56
};
var {productid,productName} = product; -->here inside flower bracket, the names should be same as property name from the object. we cannot give different names
toString() --will return all the values in the array in string using comma
ex:
var levels:Array<number> = [10,20,30,40,50];
console.log(levels.toString());
output : 10,20,30,40,50
join --will return all the values in the array in string but not using comma but by using the separator which we use in the join method
ex:
var levels:Array<number> = [10,20,30,40,50];
console.log(levels.join("-"));
output : 10-20-30-40-50
Slice --will return values given from startindex to less than endindex.
ex:
var levels:Array<number> = [10,20,30,40,50,60];
console.log(levels.slice(2,5));
output : 30,40,50
30 --->has index 2
50--->has index less than 5
var levels:Array<number> = [10,20,30,40,50,60];
console.log(levels.slice(2)); ---->if there is no end index then from start index it will print all elements to the end
output : 30,40,50,60
Splice --> will start at deleting the elements from the startindex and delete the no of elements in array given by endindex and also insert given elements if said to do so at the deleted locations
ex:
var levels:Array<number> = [10,20,30,40,50,60];
levels.splice(1,3);
console.log(levels.toString());
output : 10,50,60
var levels:Array<number> = [10,20,30,40,50,60];
levels.splice(1,3,88,99);
console.log(levels.toString());
output : 10,88,99,50,60
Push-->inserts element at the end of the array
Pop-->removes the last element from the array and returns it
Functions
--------------
Functions : syntax
function add(num1:number,num2:number):number{
return num1+num2;
}
optional parameters -->you need to mention ?
function add(num1:number,num2:number,role?:string):number{
return num1+num2;
}
default values -->here we have already passed default values to the parameter so if we do not pass also ok
function add(num1:number,num2:number,role:string="normal user") : number{
we can pass function as an parameter to another function with "ANY"dataType
ex:
function add(num1:number, num2:number):number{
return num1 + num2;
}
function calculator(xyz:any):void{
console.log(xyz(100,200));
}
calculator(add);
we can also return functions from within another function
function getSub():any{
function subtract(num1:number,num2:number):number{
return num1-num2;
}
return subtract;
}
var minus = getSub();
console.log(minus(10,5));
Ananymous function--->function which does not have any function name and it assigned to some variable
/*Anonymous function*/
var x = function(s1:string):string{
return "hello " + s1;
}
console.log(x("Typescript"));
typeof -->tells what type of data is passed in
Function overloading
------------------------------
function doubleMe(x:any){
if(x && typeof(x) === "number"){
console.log(x*2);
}else if (x && typeof(x) === "string") {
console.log(x + "" + x);
}
}
doubleMe(5);
doubleMe("John");
doubleMe(false);
here in the above function we are not restricting to any datatype. So to restrict to specific data types then we need to add function signatures
function doubleMe(x:number);
function doubleMe(x:string);
function doubleMe(x:any){
if(x && typeof(x) === "number"){
console.log(x*2);
}else if (x && typeof(x) === "string") {
console.log(x + "" + x);
}
}
doubleMe(5);
doubleMe("John");
doubleMe(false); ---->This will not allow becuase we have add two function signatures of number and string
we can pass lot of parameters using REST parameters so the functions which accepts these kind of parameters are called variadiac functions. we use "..." triple dot operator for it. This ... variable is array datatype internally. This "..." triple dot operator should be the last parameter inside function, if in case you have declared any other datatypes
var product = function(...nums : number[]){
var result = 1;
for(var i = 0; i<nums.length;i++){
console.log(nums[i]);
result *= nums[i];
}
return result;
}
console.log(product(1,2,3,4,5,"hello")); --->here we cannot inject string value becuase we have restricted ...nums to number array data type
Arrow functions or lambda functions
-------------------------------------------------------
-->they are shortcut to anonymous functions.
syntax :
var product = (x:number) => x*2 ; --->This is has parameters so inside parenthesis we have given parameters
var print = ( ) =>console.log("hello"); ---->This is has no parameters so inside parenthesis we have not given parameters
we can explicity use return keyword but it should be used inside flower bracket
var product = (x:number) => { return x*2 };
or if we have multiple lines of code then it should be written inside flower bracket
var product = (x:number) => {
x = x * x;
return x;
}
here there is no "function" keyword, there is no "return" keyword[becuase return keyword is implicit] , there is no function name;
var - this is function scoped variable. This variable will attach to window object so it is available for the whole page. Same variable name can be re declared every time with different values
let - this is blocked scoped ( if, while, for loop) variable. still this is not supported by all old web browsers where there is ES6
const - this is same as let. Difference is variable values cannot be changed. The name implies it also the same. But we can change properties values of an object declared as const
declare - this is used when we import external libraries
INTERFACE
----------------
we have created object using object literal syntax earlier, we cannot make sure that this object is created consistently across for whole project. That is some developer miss to assign value to some properties or may not use any two properties.so to prevent of such happening and to have a standard set of rules we go for interface.
var product = {
id: 1001,
Name: "Headphone",
Price: 1654.56
};
Interface defines all the rules that a class,function,arrays etc should strictly follow. interface act like a contract. interface only define properties of an object but not initialization. please dont confuse with inheritance interface, this interface is not for that.
interface is only for compile time and when once javascript is created then there is no concept of interface. you wont see any interface declarations inside js file. it means that interface does not exists at runtime.
interface product {
id: number;
Name: string;
Price: number;
display( ) : void
}
we can also make some of the properties as optional like below
interface product = {
id: number;
Name: string;
Price?: number;
display( ) : void
};
there is also called functional interface where we only decalare function name,parameters and its types and its return type.
interface add{
(x:number,y:number):number
}
var result:add = function(x:number,y:number):number{
return x+y;
}
console.log(result(5,5));
return type in function interface is optional not mandatory.
if return type is void in function interface then we can overide to any return type which we wish when we define the functions. But if you specify return type other than void then you cannot change it when we define the functions.
we can also define function in object interface
interface productfunc{
id:number;
name:string;
price:number;
description?:string,
display() : void
}
var collData : productfunc = {
id :123,
name :"Headphone",
price : 1555.45,
description : "Philips headphone",
display() : void {
console.log(this.id + "-" + this.name);
}
}
console.log(collData.display());
output : 123-Headphone
array index interface
------------------------------
we can define two types here
array which has index of type integer for accessing
array which has index of type string for accessing --->
index wise
---------------
we can also define array interface as shown below
interface studentName {
[index:number]:string
}
var resStudent : studentName = ["John","Mathew","Robin"];
console.log(resStudent);
console.log(resStudent[1]);
array which has index of type string for accessing--->these are internally represented as an object literal with unlimited number of properties
we can extend the interface like below
interface exterior{
color:string,
doors:number
}
interface interior{
type:string,
gear:number
}
interface car extends exterior,interior{
make:string
model:string
}
var carObj : car= {
make:"Tata",
model:"2021",
color:"white",
doors:4,
type:"manual",
gear:5
}
console.log(carObj);
output:
{
"make": "Tata",
"model": "2021",
"color": "white",
"doors": 4,
"type": "manual",
"gear": 5
}
Comments
Post a Comment