Type Script
Type Script
Type Script
TypeScript Definition:
This means that any valid .js file can be renamed to .ts and compiled with
other TypeScript files.
TypeScript is Portable:
Compilation:
Language:
Declaration Files:
• Modules
• Functions
• Variables
• Comments
console.log (message)
Let us see how to compile and execute a TypeScript program using Visual
Studio Code. Follow the steps given below
Step1. Save the file with .ts extension. We shall save the file as Test.ts.
The code editor marks errors in the code, if any, while you save it.
Step 2 − Right-click the TypeScript file under the Working Files option in
VS Code’s Explore Pane. Select Open in Command Prompt option.
Step 3.To compile the file use the following command on the terminal
window.
tsc Test.ts
Step 4.The file is compiled to Test.js. To run the program written, type the
following in the terminal.
node Test.js
Compiler Flag:
Compiler flags enable you to change the behavior of the compiler during
compilation. Each compiler flag exposes a setting that allows you to change
how the compiler behaves.
S.No. Compiler flag &Description
1. --help
2. --module
3. --target
4. --declaration
5. --remove Comments
6. --out
7. --sourcemap
8. --module noImplicitAny
9. --watch
Identifiers Are:
num1 first-name
$result 1number
TypeScript Key:
continue do catch
TypeScript ignores spaces, tabs, and newlines that appear in programs. You
can use spaces, tabs, and newlines freely in your program and you are free
to format and indent your programs in a neat and consistent way that makes
the code easy to read and understand.
TypeScript is Case-sensitive:
Comments in TypeScript:
class Greeting {
greet ():void {
obj.greet();
The above example defines a class Greeting. The class has a method greet
(). The method prints the string “Hello World” on the terminal.
The new keyword creates an object of the class (obj). The object invokes
the method greet ().
function Greeting () {
}
Greeting.prototype.greet = function () {
};
return Greeting;
}());
obj.greet()
Ans: 1.Unified UX
2. Fluid UX
Q2.What is Solution?
Ans: 1.Better I will Build a SPA (AngularJs) For you world popular SPA Twitter.
YouTube is a Podcasting.
jQuery HTML
Then why Angular AngularJs.
Q6.
Basic Requirement to build End to End Web Application:
Language/Tool
Description
HTML This is a markup Language
used for Presentation.
Database:
It defines the data, queries, reports and analysis required for application.
Middleware:
It is a software framework used in Multitier Application to handle communication
DTP:
Publishing Tools Required for Publishing Images and Animation for web
Note:
A Software Stack can be used for building End to End Application, Which includes
MEAN, MERN etc.
M-MongoDB [Database]
E-Express [Middleware]
R-Reactjs[ClientSide]
1. Unified UX
A web application must reach broad range of devices ie.from Browser to mobile
• Application must have the same feel and look across devices.
It is nothing but User must get access to everything from one Page.
• There must not be any navigation between Pages.
• New details are updated into Page without reloading the Page.
HTML has normal elements, void elements, RC Data elements, Foreign key
elements.
• Routing Issues.
Ex: How new updates are added to the Page without reloading?
• Blackboard System
• Broken Pattern
• Implicit Invocation
• Layer
• Micro Services
• Model-view-controller(MVC)
• Presentation-abstraction-control
• Model-view-presenter(MVP)
• Model-view-view Model(MVVM)
Library:
Framework:
Q11.What is AngularJs?
Ans: It is not Designed for what we use are using.It have lot of Gap's.
[As-Is,To-be,GAP]
Q13.What is Angular?
3.Angular is a complete rewrite from the same team that buld AngularJs.
4.Angular uses TypeScript ,which is class based OOP and Strictly Typed.
Angular2-> September14,2016
Angular5->November 1st,2017
Angular7->October 18th,2018
TypeScript:
1.TypeScript is an open source programming language developed and maintained
by Microsoft.
2.It is a strict syntatical superset of JavaScript and adds optional static typing to
language.
2.The standalone compiler is responsible for translating the TypeScript code into
Target JavaScript.
4.Vs Shim is responsible for defining the rules for Language that can be
CrossCompiled into JavaScript
6.The Editor tools defines the language rules foe specific Environment.The various
Editors are Vscode,Sublime,WebStorm,Brackets,etc...
Type Annotation:
The Type Annotation in Compiler programming refers to the type signature that
defines input and output type for a function.
Type Inference:
It determines the datatypes of value implicitly and handles specific type
dynamically.
TypeScript:
function f1(a:number,b:number)
function f1<T>(a:T,b:T)
f1<number>(10,10)
f1<string>("A",10)
Generics:-
Generics refersto type safe and strongly typed for specific type of value
dynamically.It identifies the type and infer the type.ie.Generics
Interface:
Interface defines a contract that is rules for designing a comment.
Async/Await
Await for first request wait until response come and wait until response come.
Async will not wait for response all are light weight.Async will not wait it will
movecan to next one.
Asynchronous:
It refers to an Asynchronous process where a request is made and will not wait
for response.it proceeds to the next whenever response is ready it will start the
process.
Package Manager->NPM,Composer,Grunt,Growl,yarn,Nuget
C:Users\Administrator>node _v v10.15.0
c:Users\Administrator>
WebStrom,Sublime,Vs,Ecllipse
[IDE]-Build ,Test,Application
Windows
https://nodejs.org/en/download/[.msi] file
Test:
Note:
you can get the Package names their various and bugs information and goto site
>npm -v->"https://www.npmjs.com"
Angular App
_TypeScript
ctrl+backTick[`]~
Search
D:\TypeScript
3.Name it as "demo.ts"
console.log("welcome to TypeScript");
ctrl+`[backtick]
1.open Terminal
ctrl +
2.Link js file
<head>
<script src="demo.js"></script>
</head>
->Now you can right click on HTML files and Openin Browser.
D:\TypeScript>tscdemo.ts
D:\TypeScript>node demo.js
Variables in TypeScript:
Variables are named storage locations in memory,where you can store a value
and use it as a part of any expressions
HomePage:
Example:
<html>
<head>
<script>
"use strict":
function f1( ){
x=10;
document.write("x=" + x);
f1( );
</script>
o/p: x=10
a)var
b)let
c)const
let b=20
const
console.log("a="+a+"\n"+"b="+b+"\n"+"c="+c);
>tsc demo.ts
>node demo.js
var x=10;
if(x==10){
let y=20;
log(x=+x,y=+y)
function f1()
var x=10;
if(x==10){
value must be Initalized while declaring itself we need to declare value for it.Same
name Identifier must be there with different values.
function Outer( ){
var x=10;
function inner( ){
var y=20;
console.log("x ="+ x );
TypeScript Language:
Varables in TypeScript:
Variables are storage locations in memory.
Where you can store a value and use it as a part of any expression.
console.log(x);
• var
• let
• const
Keyword Description
var Scoped Variable so that it
is accessable from any location in the
function.It allows Shadowing
ie.Same name Identifier with different value.
var x=10;
if(x==10){
let y=20;
}
Syntax: Shadowing
function f1()
var x=10;
if(x==10){
let y=30;
function f1(){
const x; //Invalid
"use strict"
function f1( ){
const x;
x=10;
let x;
function f1(){
const x;
x=10;
TypeScript Variables:
TypeScript Variables will not support hoisting.It is a process supported in
JavaScript where the translator Executes the code declaration followed by
rendering.
x=10;
console.log("x="+ x);
let x;
}
Window related to Browser
function f1( ){
console.log("y in f1="+y);
function f2( ){
console.log("y in f1="+y);
f1( );
f2( );
function f1( ){
var name="John";
var name="Dhoni";
console.log(name);
f1( );
D:\TypeScript>ts demo.ts
let Name="John";
b)Variable name must start with an alphabet or _and can contain alpha
numeric with_.
var id=10;
Variables in TypeScript:
Data Type:
It determines the type of value that can be stored in a given memory reference.
• LIFO
• value types.
a. number
b. boolean
c. string
d. undefined
e. null
TypeScript DataTypes:
I. The Data Type determines Type of value that can be stored in a reference.
II. The TypeScript Data Types are categorized into two Types:
a. Primitive Types
Primitive Types:
1.The Primitive Types are Stored in a Memory Stack.
a. number
b. boolean
c. string
d. undefined
e. null
Number Type:
Unsigned Integer=10
Floating Point=3.5
Double=340.560
Decimal=4.556979794 -29
let Signed:number=-10;
let Unsigned:number=10;
let float:number=4.5;
let double:number=450.560;
let decimal:number=4.55697979795932;
let exponent:number=2e3;
console.log="Signed="+Signed+"\n"+"Unsigned="+Unsigned+"\n"+"Float="+Float
+"\n"+"decimal="+decimal+"\n"
The number Type in TypeScript is used to handle numerical values which includes
the following number Type:-
UnSigned Integer 10
Double 340.560
Hex oxfood
Binary 0b1010
Octal 0o174
Example:- "DataType.ts"
let UnSigned:number=10;
let float:number=4.5;
let double:number=450.560;
let decimal:number=4.556979795932;
let exponent:number=2e3
console.log("Signed="+Signed+"\n"+"UnSigned"+UnSigned+"\n"+"Float="+float+"
\n"+"Double="+double+"\n"+"Decimal="+decimal+"\n"+"Exponent"+exponent)
output: Signed=-10
UnSigned=10
Float=4.5
Double=450.560
Decimal=4.556979795932
Exponent=2000
Boolean Type:-
The Boolean type is True/False 1/0
1. The Boolean type allocate a binary type of memory that holds the address
for a number but stores the values True (or) False.
2. The Boolean Type over Mathematical operation will define 1 for "True" and
0 for "False".
3. However Boolean Type Reference can store only two keywords True or
False.
4. The Boolean Condition are also satisfied by using the keywords "True" or
"False" or "0" or "1".
let iSinvalid:boolean=false;
console.log(isValid+isInValid);//1
console.log(isValid) //true
if(isValid==1)//inValid Expression
string type
" "
' '
let year:number=2019
you have to bind a string with expressions that how we need to bind
>node Stringtype.js
D:\\Images\Cars\\pic.js\
ps D:\TypeScript
3.String Type:
A string represents group of characters enclosed in codes.a string can enclose
alphabet,number or special characters.
Closure Description
Syntax1: string
let msg:string="welcome";
let msg:string="alert('hello')";
let year:number=2019;
o/p: D:Imagescar.jpg
let path:string="D:\\Images\\car.jpg";
o/p: D:\Images\car.jpg
o/p: "welcome"
Undefined:
if(price==undefined)
else {
console.log("price="+price);
console.log(" x= "+ x );
function GetName( ){
let uname:string;
uname=prompt("Your Name:");
if(name==" "){
else if(name==null){
document.write("you cancelled")
else{
>tsc nulltype.ts
>node nulltype.js
"nulltype.html"
<DOCTYPE html>
<html>
<head>
<script src="nulltype.js"></script>
<script>
function bodyload( ){
GetName( );
</script>
prompt box:
uname=prompt("Your Name");
if(uname==" "){
else if(uname==null){
document.write("you cancelled");
else{
document.write("you cancelled");
}
else{
document.write("Hello!"+ uname);
2.compile Ts File
>tsc nulltype.ts
>node nulltype.js
<!DOCTYPE html>
<html>
<head>
<script src="nulltype.js">
<script>
function bodyload( ){
GetName( );
</script>
</head>
</body>
</html>
Hello!Jonson
Non-primitive Types:
1. The Non-primitve Types are stored in memory heap.
3. The heap memory doesn't have any fixed size.Hence,the value range varies
according to the browser.
1.Array Type
2.Object Type
Array Type:
a. Reduce OverHead.
b. Reduce Complexity.
I. It reduce OverHead by storing values in Sequential Order.
II. It reduce the Complexity by storing multiple values under one Reference.
Ans: MetaCharacters * ?+ [ ]
* Astrik=Many
+=One or More
?=one
[ ]=Range
dir p*.*
dir t p*.*
3.Array reduce complexity by storing multiple values under one reference name.
6.TypeScript Array can also restrict an Array to handle specific type of Values.
7.The Array Types are defined by using the meta character the open close brase "[
]"
let Values:string[ ];
Values[0]="A";
Values[1]="B";
Values are dynamically assigned values into array.If you are not resolving error
Q.What is the difference between the Values for Square and Array Constructor?
Array Manipulations:
i. Reading Values from an Array.
• toString( )
• join( )
• Slice( )
toString( )->Reads the values from Array and return Values from Array
console.log(products.join());
or Slice(1,3)
Note:
Function Description
"|","-->"
Example:
console.log(products.toString());
//output:Tv,Mobile...
console.log(products.join("|"))
//output: Tv/Mobile/...
console.log(products.slice(1,3));
//output[ 'Mobile','Sunglasses']
• push( )
• unshift( )
• splice()
Example:
console.log(products.toString( ));
products.push("watch","Mouse");
console.log(products.toString( ));
command prompt
>tsc arraytype.ts
>node arraytype.js
push.ts
Output:
Rest operator :
It is used to pass many values.
Function Description
push( ) Append it is
used to append a new element
as last element.
unshift( ) It is used to append a
new element into
Array as first element.
splice( ) It is used to add new
element into Array at any specified index.
Array.ts
output:
5)Removing Elements from Array:
Function
Description
1.pop( ) It remove & returns the last element in
an Array.
2.Shift( ) It removes and returns the first Element in
an Array.
3.Spilce It remove a specified element from a
Array based on the given index no.It
return an array of remove elements.
pop
output
pop
output
//Watch Removed
shift
output
//Tv removed
splice
output:
//Mobile Removed
Validating an Email
name.123@gmail.com
dotposInDomain=Str.IndexOf(".");
str.Slice(dotpos);
Slice(4,1);
Slice(4)
output
Example: filter( )
output:
Example:Sorting
output:
Sorting Array Element:
Function
Description
Sort( ) A Function is sort
Arranges array elements in
ascending order
reverse( ) Arranges array element in
the reverse order ie from bottom to top.
6.concat Array
you can combine Array elements from Multiple Arrays and Store in a Single
Array.The function "concat( )" is used for combining Array elements.
output:
Q.How do we declare to handle any Type of elements?
Ans:Object encapsulation a set of members logical Entity that hold the
code.Object reference to class and reference.Object is a collection of members,It
contain Members,Properties and Methods.These properties and Methods are
related to object Events are related to Browser.Events are associated with
browser not object Events are used by object.The behaviour of object is exihibited
building an object is a set of properties and Methods.
Object Type:
1. JavaScript is an object based Programming.
2. TypeScript is an object oriented programming
3. In both Programming approaches object is an logical Entity that
encapsulates a set of Properties and Methods.
4. An object allows to reuse the components without redefing.
5. An object encapsulates the members in "{ }".
6. Object is by default static type hence its members are accessed directly by
refering to Object name.
let button:any={
width:100,
height:20,
value="Default"
close:function( ){
return "closes the window";
},
open:function( ){
return "Opens the Window";
},
button.value="close";
console.log("Button
Text="+button.Value+"\n",+"Close
Method="+button.close( ));
button.Value="open";
console.log("Button
Text="+button.Value+"\n"+"open
Method"+button.open( ))
Json Type:
Json type will be Array of object.
Array of object[JSON-JavaScript object Notation]
"json.ts"
let products:any[ ]=[
{
Name:"Tv",Price:34000
Name:"Shoe",Price:12000
}
];
console.log("Shoe Price="+products[1].Price);
},
output:
Regular Expression:
isNaN( )->is not a Number
var x=10;
even or odd
var mobile ="+91 10 digits"
It uses a pattern
pattern referes to a format.patterns are built using Meta characters and
Quantifiers.patterns are enclosed in '//'.pattern refers to a format.* represents
zero or many.Regular Expression are always verifief with match( ) function.
3.Regular Expression Type
1.A Regular Expression is used to verify the format of input value.It uses a pattern
that is enclosed in "/ /"
2.The pattern are built by using Meta Characters and Quantifiers.
3.The commonly used Meta characters ara shown below:
Meta Characters Description
^ It matches
the starting position within a
string
. It matches
any single character or Exactly
specified character.
\ It refer any
Entity within the Expression.
$ It matches
the ending position within a string.
* It matches
the string preciding with zero or
more Elements
? It matches
the preciding element zero or one
time
+ It matches
the preciding element one or
more times
w It matches a
word that is alpha numeric with(under
score) _
W It represents a
Non-word
d It Specifies a
Number with decimal places
D It is to refer
UnSigned Number.
s allows
leading spaces.
S no space
allowed.
[ ] It defines range or
Specific Value.
[A-Z] only uppercase
letters allowed.
[a-z] only lowercase
allowed.
[a-zA-Z] or [a-Z] Both Upper & Lower case .
[0-9] Only numeric.
[a-zA-Z0-9] or \w alpha numeric
[a,d,f] only specified
characters
[^a,d,f] exclude specified
chars.
[a-mA-M4-9] chars in specified range.
\+\-\-\$\@ special chars group
[!@#$%&] special char group
(?=.*[A-Z]) Atlest one uppercase
letter
(?=.*[0-9]) Atleast one number
(?=.*[!@#$%&] Atlest one special character.
Qunatifiers
Description
{n} Exactly n-number of
chars
{n,m}
minimum-n,maximum-m
{n, } minimum-n,maximum
any
{4}
{4,10}
{4}
Syntax:
let regExp:any=/[A-Z]{4,10}|;
Note: A regular Expression is verified with the value using "match( )" function.It is
a boolean function that returns true,when the expression matched.
Example:- Regular Expression
let pwd:string="Jonson123";
let regExp:any=/(?=.*[A-Z])\w{4,15};
if(pwd.match(regExp)){
console.log("Verified");
}
else{
console.log("Invalid Password")
}
output:
output:
TypeScript DateTime:
I. A DateTime can hold a date and Time value.TypeScript uses any Type to
store date value.The Date value is stored in in memory as string allocated
by date constructor "Date( )"
II. Syntax: let mfd:any=new Date("2019/05/06")
III. The date values are accessed and used by using Date( ).Date function which
return a date and time number.
Date Function
Description
getHour( ) Returns the hour
number in 24hr format.
getMinutes( ) Returns the Minutes number
fromTime.
getSeconds( ) Returns the Second Number.
getDate( ) Returns the Current date number ie
"7"
[05/07/2019]
getDay( ) Return the weekday number
0=Sunday
getMonth( ) Return Month number 0=Jan
getFullYear( ) Return full year 2019.
getYear( ) Return full year as
per y2k/19.
toLocale DateString( ) Return shortdate
toLocale TimeString( ) Return shorttime
let mfd:any=new Date("2019/05/06");
let month:string[ ]=["Jan","Feb","Mar","Apr","May"];
console.log("Manufacture
Month="+months[mfd.getMonth()]);
console.log("Mfd Year="+mfd.getFullYear( ));
console.log("Mfd="+mfd.toLocaleDateString( ));
output:
Summary of Data Types:
1.Variables
2.DataTypes
3.Operators-In computer programming operator is an object that
evaluates an value by using operands.
4.Statements
Subtraction find difference value:
string-string
number-string
boolean-boolean=number
boolean-number=number
boolean+string=string
TypeScript Operators:
An operator in computer programming is an object that evaluates any value by
using operands.
The Operator is defined as unary,binary and ternary based on the number of
operands it uses
Single operand-Unary
Two operands -Binary
Three-Ternary
The operators are categorised into several groups based on the type of value they
return.
1.Arthematic Operator
2.Comparision (Relational) Operator.
3.Bitwise Operator
4.Logical operator
5.Assignment Operator.
6.Special Operator.
Arthematic Operator:
character Description
Example
+ Addition
10+20=30
- Substraction 20-10=10
* Multiplication
10*20=200
/ Division 20/10=2
% Modulus 21%10=1
(Remainder)
++ Increment var a=10;
a++;Now a=11;
-- Decrement var a=10; a--;Now a=9;
** Exponent
2**3=8
Post Increment:-
It assigns the initialised value and increment thecurrent value
let x:number=10;
let y:number=x++;
console.log("X="+x+"\n"+"Y="+y);
output:
Pre-Increment:-
It Increments the intialized value by 1 and then assigns
output
Exponent ** Math.pow(2,3)
Exponent:It is suppoerted in TypeScript not in JavaScript.Js will use "Math.pow(
)".js will use "Math.pow( )" function for finding the base raised to power
Syntax: let x:number=2**3; Ts-8
var x=Math.pow(2,3);Js-8
Comparision Operator:
Operator Description Examples
== Isequalto 10==20=false
=== Identical(equal and
10===20=false
of Same Type)
!= NotEqualto
10!=20=true
!== Not Identical
20!==20=false
> Greater than
20>10=true
>= GreaterThan or Equalto
20>=10=true
< Lessthan 20<10=false
<= Lessthan or Equalto
20<=10=false
Id===Id Field name must be id and Type
Id==Id It will not compare type.it will only Compare
Value.
output:
output:
4.Instanceof Operator:
Instance of is Special Operator that Verifies Wheather the Specified
Object is derived from given class.It returns Boolean true,If the Instance
is Specified class type.
Syntax: yourObject instance of yourclass;
Example: let product:any={
Name:"Tv",
Price:45000
};
console.log("product is an object="+product instanceof Object));
output
6) "in" Operator
It is a Special Operator used to verify whether the given property is avalible in an
object it returns boolean false if property "Not Found" .
Syntax:
"PropertyName" in Object;
"Tv" in product
Tv is Value Name is a property
Example:
let product:any={
Name="Tv",
Price:45000,
IsInStock:true
};
if("Price" in product){
for(var property in product){
console.log("property+":"+product[property]+"\n");
}
}
else{
console.log("Price Missing");
}
output:
7)Of Operator:
It is a Special Operator used to verify the values of an given object
and return the values.
Example:
let cities:string[ ]=["Delhi","Hyderabad"]
for(var item of cities){
console.log(item);
}
output:
Union Types:
• TypeScript is Strictly Typed
• You can define a reference to handle "any" type of value by using
"any" datatype.
• TypeScript supports union Type that allows to create a reference that can
handle various types that restricted with only specified.
output:
TypeScript Statements:
A Statement in computer programming is used to control the Execution flow.
The type of statements the TypeScript can Handle are categorized into following
groups:
StatementType Keyword
Selection
if.else,switch,case
Loop &Iteration Jump for,while,dowhile
Jump break,continue,return
Exception Handling try,catch,throw,finally
TypeScript OOPS:
• TypeScript is an class based Object Oriented Programming
• JavaScript is an Object based Programming.while is psuedo OOP IE.OOP like
Programming
• The OOP Concepts were Introduced in the Early 1960's by Jhon Olay &
Nyguard
• OOP was formulated with a language called SIMULA-67
Features of OOP:
• Support Code Reusability
• Supports Code Extensibility
• It is Complex in Configuration
Characterstics of OOPS:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
code can be extended by a feature called Inheritance
OOPS Terminology:
Term
Description
class It is a Model or Blue print for creation of
objects.It is a logical Entity that holds that encapsulates the
logic
object It is a physical representation of logical Entity
Properties Defines the Physical Description of an object
Methods Specifies the actions to be performed by an object
Event Sends aMessage to the Subscriber inorder
to notify change
Readonly Members:
Interface members are by default overridable.ie you can redefine the
value after Initialization.
Syntax:
interface IProduct{
Name:string;
}
let product:IProduct={
Name="Tv";
}
product.Name="Samsung Tv";//valid
console.log(product.Name);
output:
output: