TypeScript
TypeScript
Q. What is Angular?
Angular is a developers platform. Developers platform means Angular provides support
from end to end i.e provides support from building to deployment. Angular provides all
the languages, library & tools required for developer.
Fluid UX: It means the user don’t need to go every pages. The user will stay in one page
and access all the things in the same page.(SPA)
Loosely coupled and Extensible: Loosely couples means we can add new things without
affecting the existing things.
The only solutions for this is Building SPA(Single Page Application).SPA has all the
features like Unified UX, Fluid UX.
Lot of DOM Manipulations, Heavy on application, Lot of AJAX explicitly & Lots of coding.
The Solution for this building SPA using Angular, React, Vue, Backbone, knockout etc.
Q. Why we need Angular?
To build single page applications only. It is a Java script framework which reduces the
efforts of developers. It provides language, libraries & tools required to develop
applications.
ANGULAR JS:
- Google introduced Angular JS in 2010 for building SPA.
- Angular JS is open source and cross platform framework developed by google and
maintained by a large community of developers and organizations.
Angular JS is not designed for what you are using. Hence lot of GAPS(Gaps means the
technology cannot fulfil all the needs).
- Angular JS uses JavaScript as Language.
- JavaScript is not strongly typed language.
- JavaScript is not an OOP language.
- Extensibility issues.
- Not Loosely Coupled
- Google Developed Angular JS versions Up to "1.8"
- Google Introduced "Angular" in 2014 as Version 2
Page 1 of 42
ANGULAR-2:
- Google re-built complete technology as "Angular 2"
- Angular 2 is not a replacement for Angular JS, It is just as alternative.
- Angular 2 Features
a) It uses "TypeScript" as a language.
b) TypeScript is an OOP language.
c) Modular Library(Lightweight Library)
d) Light weight
e) Faster
f) Reduced GAPS
- Angular Latest is "15"
@ React uses one way databinding and supports virtual DOM whereas Angular uses two-
way data biding and supports real DOM.
@ React provides support for adding Java script libraries to source code where as
Angular JS does not provides.
Page 2 of 42
Q. What are the issues with JavaScript?
- Not Strongly Typed Language.
var x = 10;
x = "John";
** TypeScript **
SUMMARY
@ TypeScript Evolution – History (4)
@ TypeScript Features (4)
@ TypeScript Architecture (4-5)
@Typescript Environment Setup (5-7)
@ TypeScript Language Basics (7-22)
* Variables (8-10)
* Data Types (10-20)
* Operators (20-21)
* Statements (21)
* Functions (21-22)
@ TypeScript OOP (23-40)
* Contracts (24-27)
* Class (27-34)
* Inheritance (34)
* Polymorphism (34-36)
* Templates (36-37)
* Enum (39)
* Generics (37-39)
@ TypeScript Modules (40-43)
Page 3 of 42
Introduction to TYPESCRIPT
- It is a super set of Java script. It is strongly typed.
- It is strictly typed.
- It is an OOP language.
- It is built in TypeScript. TypeScript uses compile time checking.
- It can directly interact with hardware.
- Less memory, Faster, Light Weight
- It is used in building large scale applications.
Note: Browsers can't understand TypeScript So, TypeScript is translated into JavaScript.
TypeScript Architecture
1. Core Compiler
- Core compiler translates the typescript code into machine code.(Verifies The Error in
the program)
- core. ts : It verifies the keywords
- program. ts : It verifies the program structure. Check the syntax whether semicolon
is misses or not & check other syntax also.
- parser. ts : It is responsible for converting one type to another
- checker. ts : It is responsible for data type checking.
- scanner. ts : It is responsible for handling input.
- emitter. ts : It is responsible for handling output.
Page 4 of 42
4. TsServer [server.ts]
- Hosting(Putting our developed application on Internet)
- Request and Response
- TypeScript programs are hosted, compile and managed on server.
5. VS Shim [shims.ts]
- It makes the typescript program cross platform. (cross platform means the software
/program can able to run in any OS like Windows, MacOS, Linux)
- TypeScript Program => Compiler => IL Code => Shim => Managed Code
- Managed code is suitable for all OS services.
Note: CAPTCHA is developed through AI. A Java developer cannot develop a CAPTCHA.
CAPTCHA is used to verify whether you are a human or Robot.
Editor is a platform where we write our program, compile and run our program.
https://nodejs.org/en/
C:\>node -v
C:\>npm -v
Note: Make sure that your Node version is > 14 and NPM version > 6.
Page 5 of 42
https://code.visualstudio.com/
http://editorconfig.org/
E:\typescript-project
3. Open Terminal
E:\>npm init -y
This will generate package. json, which comprises of project meta data.
- App Name
- Version
- Copyright
- License
- Dependencies
- Author etc...
Page 6 of 42
3. TypeScript 4. Create Project
Note:
If you face any problem like “running scripts disables” then type below three commands
Note:
- Every TypeScript file will have extention ".ts"
- Transcompile the TypeScript file into JavaScript
index.ts
>tsc index.ts
- It generates "index.js"
- If your code comprises of presentation related to DOM then link "index.js" to any
HTML page.
- If your code comprises of console methods without any DOM then you can directly run
JavaScript program using node compiler.
>node index.js
EX:
1. Go to "Src" folder
2. Add a new file
"index.ts"
var username:string = "John";
document.write("Hello ! " + username);
Page 7 of 42
4. Transcompile
> tsc index.ts [generates index.js]
5. Go to "index.html"
<head>
<script src="src/index.js"> </script>
</head>
Test from Console:
1. Go to index.ts
var username:string = "John";
console.log("Hello ! " + username);
2. Transcompile
> tsc index.ts
a) Declaration:
b) Assignment
c) Initialization
var x; => Declaring
x = 10; => Assignment
var y = 20; => Initialization
a) Var :
- It defines a function scope variable.
- You can declare in any block of a function and access from any another block.
- It allows declaring, assignment and initialization.
Ex:
function Demo()
{
var x;
x = 10;
if(x==10)
{
Page 8 of 42
var y = 20;
}
console.log("x=" + x + "\n" + "y=" + y); // 10, 20
}
Demo();
- It allows shadowing.
- Shadowing is the process of re-declaring or re-initialization of any variable
within the scope.
Ex:
function Demo()
{
var x;
x = 10;
if(x==10)
{
var y = 20;
var y = 30; //shadowing
}
console.log("x=" + x + "\n" + "y=" + y); // 10 30
}
Demo();
- It allows hoisting. Hoisting means we can use variables before declaring it.
- Hoisting allows the compiler to access variable declaration from any location.
There is no order for declaring and using.
Ex:
x = 10;
console.log("x=" + x);
var x; // hoisting
a) Let :
- It configure block scope variable.
- It is accessible in the block where it is defined and also to its inner blocks.
- It allows declaring, assignment, initialization
- It will not allow shadowing and hoisting.
Ex:
function Demo()
{
let x;
x = 10;
if(x==10)
{
let y = 20;
console.log("x=" + x + " y=" + y);
}
Page 9 of 42
}
Demo();
a) Const :
- It is also block scoped.
- It allows only initialization. [no declaring and assigning]
- It will not allow shadowing and hoisting.
Syntax:
const x; // invalid
x = 10; // invalid
a) Primitive Type
b) Non Primitive
Syntax:
var variableName:dataType = value;
Primitive Types:
- They are immutable types. - Structure can't change
- Have fixed range for values. - Stored in memory Stack [LIFO]
Page 10 of 42
a)number b)string c)boolean d)null e)undefined f)symbol
Number
- It can handle
signed integer - 45
unsigned integer 45
floating point 34.45
double 345.56
decimal 3450.56
binary 0b101
hexa 0 to f
octa 0o495
bigint Binary [format]
exponent 2e3 2 x 10[3] = 2000
Syntax:
var price:number = 3400.56;
var rate:number = 2e3; [2000]
var bit:number = 0b1010; [10]
Ex:
const bit:number = 0b1010;
const exp:number = 2e3;
console.log("Bit=" + bit + "\n" + "Exponent=" + exp);
- To verify the input type number or not, we use the function "isNaN()".
- To convert string format numeric value into number we use
a) parseInt()
b) parseFloat()
<script>
document.write(Number.MIN_SAFE_INTEGER);
document.write(Number.MAX_SAFE_INTEGER);
</script>
String Type
Page 11 of 42
Ex:
var username:string = "John";
var age:number = 23;
var msg1:string = "Hello !" + " " + username + " " + "you will be" + " " + (age+1) + " "
+ "next year";
var msg2: string = `Hello! ${username} you will be ${age+1} next year`;
console.log(msg1);
console.log(msg2);
Ex:
var mobile:string = "+(44)(30) 2242 4563";
if(mobile.match(/\+\(44\)\([0-9]{2}\)\s[0-9]{4}\s[0-9]{4}/)) {
console.log("OTP Sent");
} else {
console.log("Invalid Mobile");
}
Boolean Type
Syntax:
var stock: boolean = true;
if(stock==1) // invalid in typescript but valid in Java script
{}
if(stock==true)// valid
{}
var name:string|number;
var username:string|null = prompt("Enter Name");
var username:string = prompt("Enter Name"); // invalid
Page 12 of 42
Null and Undefined
- Null specifies that there is no value provided into reference at run time.
Syntax:
var username: string | null = prompt("Enter Name");
Syntax:
var username: string; // invalid
console.log(username);
Note: You can verify the value defined or undefined by using following
techniques.
a) Check with undefined
if(Price==undefined)
{ }
Array Type
- Arrays are used to reduce overhead and complexity.
- Overhead means there is space & it is not used.
Page 13 of 42
- Arrays were introduces into computer programming to reduce overhead by
storing values in sequential order.
- Arrays can reduce complexity by storing multiple values under one name.
- Array can handle various types of values.
- Array can change its size dynamically.
Declaring Array:
var name :string[]; // string type
var name :number[]; // number type
var name :any[]; // any type
var name :string[] | number[] ;
Array meta character "[]" will allow to initialize or assign various types
if type is "any".
Page 14 of 42
Syntax:
var collection: any[] = [1, "TV", true];
Ex:
var collection: any[] = [1, "TV", true];
Ex:
var collection: any[] = [1, "TV", true, ["Delhi", "HYD"], function(){console.log("Function in
Array")}];
console.log(collection[3][1]);
collection[4]();
Array Methods
Reading Values:
toString(), join(), slice(), find(), filter(), map(),
for loops
for interators [in, of]
Ex:
var categories: string[] = ["Electronics", "Footwear", "Fashion"];
Note: Array supports union of types. But you can't initialized union types, you
have to assign.
Page 15 of 42
Syntax:
var collection: string[]|number[] = [];
collection[0] = 10;
collection[1] = "A";
Note: Read-only prevents the changing of array
Ex:
Syntax:
let tv = {
Key: value,
Key: value,
Key: function() { }
}
- Above syntax will not have any restriction for keys and value.
- TypeScript can set restriction for key and value.
- TypeScript object type is defined using "{ }"
Syntax:
let tv: {Name: string, Price :number} = {
Name: "Samsung TV",
Price : 45000.44
}
Syntax:
let tv : {Name: string, Price: number, Stock?:boolean} = { }
Page 16 of 42
}
console.log(`Name=${tv.Name}\nPrice=${tv.Price}`);
Syntax:
object : {
Name: string,
Total: any
}
Ex:
let tv:{Name: string, Price :number, Qty :number, Cities :string[], Rating:{Rate: number,
Count :number} , Total :any, Print?:any} = {
Name: "Samsung TV",
Price: 45000.44,
Qty: 2,
Cities: ["Delhi", "Hyd"],
Rating: {Rate:4.3, Count:600},
Total: function(){
return this. Qty * this. Price;
},
Print: function(){
console.log(`
Name=${this. Name}\n
Price=${this. Price}\n
Qty=${this. Qty}\n
Total=${this. Total()}\n
Cities=${this. Cities. toString()}\n
Rating=${this .Rating. Rate} [${this. Rating. Count}]
`);
}
}
tv. Print();
Note: Object properties are string type and value can be any type.
let tv : { "Name": string, "Price": number } = { }
Page 17 of 42
Array of Objects
Data Type : Object Type Array => { }[]
Value Type : Array of Objects => [{ }, { }]
Ex:
let students:{Name :string, Age :number}[] = [
{"Name": "John", "Age": 23},
{"Name": "David", "Age": 45}
];
for(var student of students) {
console.log(`${student. Name} - ${student .Age}`); }
(or)
let students: any[] = [ { }, { } ];
Map Type
- It is same like object with and key and value.
- Key & value can be any type.
- In object keys are only string type only
- Map is faster that object
- It have implicit methods
set(), get(), has(), clear(), delete(), values(), keys(), entries()
Syntax:
let data: Map<any, any> = new Map();
data. set(1, " ");
data. set("", 0);
data. keys()
data. values()
Page 18 of 42
getSeconds() getMonth() setHours()
getMilliSeconds() getFullYear() setDate() etc...
Ex:
let Mfd:Date = new Date("2023-01-02 10:20:32.89");
console.log("Mdf=" + Mfd. toLocaleDateString());
Symbol
- It is a primitive data type of JavaScript introduced with E6. [ECMA Script 2016]
- It is used to configure a unique reference for object.
- It is hidden in iterations but accessible individually.
Syntax:
<script>
let ProductId = Symbol ();
let product = {
[ProductId] : 1,
Name: "TV",
Price: 40000.44
}
</script>
Ex:
let ProductId = Symbol();
Operators
- TypeScript Operators same as JavaScript
Page 19 of 42
1. Unary ++, -- 2. Binary +, -, * 3. Ternary ?:
2**3 =8 ES5
Math. pow(2,3) =8 ES4
TypeScript Statements
1. Selection Statements
if, else, switch, case, default
3. Iteration Statements
for.. in, for.. of
4. Jump Statements
break, continue, return
TypeScript Functions
- A function is used in "Refactoring" the code.
- Refactoring is a mechanism of encapsulating a set of statements and extracting to a
function or file.
Syntax:
function Name(params)
{
statements;
}
Page 20 of 42
{} => Definition
Note: TypeScript functions are same as JavaScript but they are configured with data
type for both function and parameters.
Syntax:
function Name (param: type): type
{
}
Ex:
function Hello(username: string):string
{
return `Hello ! ${username}`;
}
function Welcome():void
{
console.log("Welcome to TypeScript");
}
console.log(Hello(" john"));
Welcome();
Page 21 of 42
}
}
Details("Samsung TV", 34000.33);
TypeScript OOPS
@ Real world application development uses 3 types of programming systems ;
a) POPS [Process Oriented Programming System]
b) OBPS [Object Based Programming System]
c) OOPS [Object Oriented Programming System]
POPS:
- It supports low level features.
- It can directly interact with hardware.
- It is faster.
- It uses less memory.
Ex: C, Pascal, COBOL
- Code reusability Issues
- Code separation Issues
- Dynamic memory issues
- Code security
- Extensibility
OBPS:
- It supports code reusability
- It support code separation
- It support dynamic memory
- It support limited extensibility
Ex: JavaScript, Visual Basic
- No dynamic polymorphism
- No code level security
Page 22 of 42
- Need more memory, Complex
- Heavy & Slow also
Contracts
- Contract defines rules for designing any component.
- Contracts are designed by using "interface".
- Interface contains the rules for designing a component.
Syntax:
interface Name
{
// rules
}
Syntax:
interface iProduct
{
Name: string; ]
Price: number; ] Objectives(These are mandatory to fulfil ]
Stock: boolean; ]
Rating?:number; => Goal(These are not mandatory to fulfil if we fulfil then better &
} if it is not fulfilled then no problem)
Syntax:
Page 23 of 42
interface IProduct
{
Name: string;
readonly Price: number;
}
let product: IProduct = {
Name: "TV",
Price: 45000.44,
}
product. Name = "Samsung TV"; // valid
product. Price = 60000.44; // invalid – readonly
Syntax:
interface IProduct
{
Name: string;
Total():number;
Print():void;
}
Ex:
interface IProduct
{
Name: string;
Price: number;
Qty: number;
Total():number;
Print?():void;
}
let product: IProduct = {
Name : "TV",
Price: 45000.44,
Qty: 2,
Total: function(){
return this. Qty * this. Price;
},
Print: function(){
Page 24 of 42
console.log(`Name=${this.Name}\nPrice=${this.Price}\nQty=${this.Qty}\nTotal=${this.
Total()}`);
}
}
product. Print();
Syntax:
interface version1
{
A:string;
B:string;
}
interface version2 extends version1
{
C:string;
}
Ex:
interface Hdfc_Version1_Contract
{
Personal: string;
NRI: string;
}
interface Hdfc_Version2_Contract extends Hdfc_Version1_Contract
{
Loans: string;
}
let low_compatible_user:Hdfc_Version1_Contract = {
Personal : "Personal Banking",
NRI: "NRI Banking",
}
let high_compatible_user:Hdfc_Version2_Contract = {
Personal : "Personal Banking",
NRI : "NRI Banking",
Loans: "Personal and Housing Loans" }
- Contract support multiple and multilevel extentions. [Inheritance]
Page 25 of 42
NRI: string;
}
interface Hdfc_Version2_Contract extends Hdfc_Version1_Contract
{
Loans: string;
}
interface Hdfc_Version3_Contract extends Hdfc_Version2_Contract
{
GovtSchemes: string;
}
let low_compatible_user:Hdfc_Version1_Contract = {
Personal : "Personal Banking",
NRI: "NRI Banking",
}
let high_compatible_user:Hdfc_Version2_Contract = {
Personal : "Personal Banking",
NRI : "NRI Banking",
Loans: "Personal and Housing Loans"
}
Ex: Multiple
interface IProduct
{
Name: string;
Price: number;
}
interface ICategory
{
CategoryName: string;
}
interface ProductContract extends IProduct, ICategory
{
Title: string;
}
let obj :ProductContract = {
Name : "TV",
Price : 45000.44,
CategoryName : "Electronics",
Title: "Samsung"
}
Class in OOP
- Class is a program template.
- It comprises data and logic, which you can implement and customize according to
requirements.
- Class have the behaviour of Entity or Model.
- If a class is mapping to business requirements then it is referred as "Entity".
- If a class is mapping to data requirements then it is referred as "Model".
- Class is used as a blue-print for creating of objects.
- Every class comprises of 2 types of configuration techniques
a)Class Declaration b) Class Expression
Page 26 of 42
a)Class Declaration & Expression:
- Class Declaration comprises of a constant set of members
Syntax:
class Product
{
// members
}
- Class Expression comprises of members, which can change according to state and
situation.
Syntax:
let demo = class {
// members;
}
Ex:
var CategoryName: string = "Electronics";
if(CategoryName=="Electronics"){
Demo = class {
ProductName = "TV";
Price = 34000;
}
} else {
Demo = class {
EmpName = "John";
Salary = 35000;
}
}
Class Members:
- Every class can contain only 4 types of members [Class Members]
a) Property
b) Method
c) Accessor
d) Constructor
Page 27 of 42
Static Members in Class:
- A class can have static and non-static members.
- TypeScript class can have
a) Static Property
b) Static Method
Static:
- It refers to continuous memory.
- The memory allocated for first object will continue to next.
- Static is used to manage continuous operations.
- Static members are declared by using "static" keyword
-Static members are accessed inside or outside class by using class name.
-Static uses more memory and leads to memory leaks.
Non-Static | Dynamic:
- It refers to discreet memory.
- It is disconnected memory.
- Memory allocated for an object will be destroyed after object finished using class.
- It is safe but is not good for continuous operations.
- Non Static members are accessed with in the class by using "this" keyword and outside
class by using instance of class.
Ex:
class Demo
{
static s = 0;
n = 0;
constructor (){
Demo. s = Demo. s + 1;
this. n = this. n + 1;
}
Print () {
console.log(`s=${Demo. s} n=${this. n} `);
}
}
let obj1 = new Demo();
obj1.Print();
Page 28 of 42
a) public b) private c) protected
Property
- Properties are used to store data.
Syntax:
public Name: string = "John";
private Price: number = 45000.44;
protected Stock: boolean = true;
Syntax:
public Cities: string[] = [ ];
public Rating:{Rate: number, Count: number} = { };
(or)
public Rating: IProduct = { };
Accessors:
- Accessor is used to give a fine grained control over any property.
- Accessors are 2 types
a) Getter
b) Setter
- Getter is used to read and return value.
- Setter is used to input and write value.
- You can read and write into a property by using accessors.
Syntax:
get aliasName()
{
return value;
}
set aliasName(newValue)
{
property = newValue;
}
Ex:
var username: string | null = prompt("Enter Name");
Page 29 of 42
var role: string | null = prompt("Enter Your Role" , "admin | manager | customer");
var productname: string | null = prompt("Enter Product Name");
class Product
{
public _productName: string | null = null;
get ProductName(){
return this._productName;
}
set ProductName(newName: string | null){
if(role=="admin"){
this._productName = newName;
} else {
document. write(`Hello ! ${username} your role ${role} is not authorized to set
product name.`);
}
}
}
class Product
{
public Name: string = "Samsung TV";
public Rating: any = {
CustomerRating: {Rate:3.4, Count:4600},
VendorRating: {Rate:4.5, Count:300}
}
get VendorRating(){
return this. Rating. VendorRating. Rate;
}
}
let tv = new Product();
console.log(`Vendor Rating: ${tv. VendorRating}`);
Methods:
- All about methods is same as in JavaScript.
- You have to configure methods with access modifier and return type.
Syntax:
public Total():number
{
return 0;
}
Page 30 of 42
public Print():void
{}
- Method is used for refactoring the code.
- Methods are mutable.
Constructor:
- Constructor configuration is same as in JavaScript
- Constructor is used for instantiation.
- Constructor is responsible for creating object for class.
- Constructor is a software design pattern.
- It is under "Creational Patterns" category.
- Constructor is anonymous.
Syntax:
class Product
{
constructor() {
} }
- It's parameters are same as method parameters.
- Constructor is a special type of sub-routine that executes automatically for every
object.
Singleton: we can say a class as singleton if it has only one object.
Ex:
class Database
{
constructor(dbName: string){
console.log(`Connected with ${dbName} Database`);
}
public Insert():void{
console.log("Record Inserted");
}
public Delete():void {
console.log("Record Deleted");
}
}
let ins = new Database("oracle");
ins. Insert();
Page 31 of 42
- In TypeScript constructor can't overload.
- It will not support static and private constructor.
Class Implementation:
- Every class is designed as per the contract.
- Contract is implemented by class.
- A class can implement multiple contracts.
Syntax:
class className implements Contract1, Contract2
{
}
FAQ: Can we define any member additionally in a class which is not configured in
contract?
Ans: Yes. [Class is a Template]
Ex:
interface IProduct
{
Name: string;
Price: number;
Qty: number;
Total():number;
Print():void;
}
interface ICategory
{
CategoryName :string;
}
class Product implements IProduct, ICategory
{
public Name: string = "";
public Price: number = 0;
public Qty: number = 0;
public CategoryName: string = "";
public Stock:boolean = true;
public Total(): number {
return this. Qty * this. Price;
}
public Print(): void {
console.log(`Name=${this.Name}\nPrice=${this.Price}\nQty=${this.Qty}\nTotal=${t
his.Total()}\nCategory=${this.CategoryName}\nStock=${this.Stock}`);
}
}
let tv = new Product();
tv. Name = "Samsung TV";
tv. Price = 45000.44;
tv. Qty = 2;
tv. CategoryName = "Electronics";
tv. Print();
Page 32 of 42
Class Inheritance:
- A class can extend another class.
- It supports single and multilevel inheritance.
- Class can't extend multiple classes. [Constructor Deadlock]
- TypeScript derived class constructor must call super class constructor.
Syntax:
class Super
{
constructor(param?){ }
}
class Derived extends Super
{
constructor(){
super(value);
}
}
Ex:
class Super
{
constructor(){
console.log("Super Class Constructor");
}
}
class Derived extends Super
{
constructor(){
super();
console.log("Derived class Constructor");
}
}
let obj = new Derived();
Abstract class is an incomplete class i.e it contains the members that are incomplete
so we cannot create an object for an abstract class.
Polymorphism
- Poly means Many, Morphos means Forms.
- The ability of any component to serve for different situations is known as
polymorphism.
- A component can have multiple behaviours.
- A component can change its behaviour according to state and situation.
- Instead of creating lot of components, you can create one component that exhibits
polymorphism.
- Polymorphism is the process of overloading the memory with different functionalities.
- A method or function can overload.
- A class memory can overload.
- An object memory can overload.
Page 33 of 42
- Technically polymorphism is a single base class reference can use the memory of
multiple derived classes.
Ex:
1. index. ts
class Employee
{
public FirstName: string = "";
public LastName: string = "";
public Designation: string = "";
public Print():void {
document. write(`${this. FirstName} ${this. LastName} - ${this. Designation}<br>`);
}
}
class Developer extends Employee
{
FirstName = "Raj";
LastName = "Kumar";
Designation = "Developer";
Role = "Developer Role : Build, Debug, Test, Deploy";
Print(){
super. Print();
document. write(this. Role);
}
}
class Admin extends Employee
{
FirstName = "Kiran";
LastName = "Kumar";
Designation = "Admin";
Role = "Admin Role : Authorizations and Authentication";
Print(){
super. Print();
document. write(this. Role);
}
}
class Manager extends Employee
{
FirstName = "Tom";
Page 34 of 42
LastName = "Hanks";
Designation = "Manager";
Role = "Manager Role : Approvals";
Print(){
super. Print ();
document. write (this. Role);
}
}
2. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="src/index.js"></script>
<script>
var designation = prompt("Enter Designation");
for(var employee of employees)
{
if(employee. Designation==designation) {
employee. Print();
}
}
</script>
</head>
<body>
</body>
</html>
Templates in OOP
- Abstract classes are used to design templates.
- A template comprises of data and logic which is already implemented partially, so that
developer and extend and complete the implementation according to client
requirements.
- Abstract class contains both methods that are implemented and not implemented.
- Developer have to implement and customize the methods that are not implemented.
- If any method is incomplete then it is marked as "abstract".
- If any one member of a class is abstract then class is marked as "abstract".
- Abstraction is the process of hiding the structure of component and providing only the
functionality.
Ex:
interface ProductContract
{
Name: string;
Page 35 of 42
Price: number;
Qty: number;
Total():number;
Print():void;
}
abstract class ProductTemplate implements ProductContract
{
public Name: string = "";
public Price: number = 0;
public Qty: number = 0;
public abstract Total():number;
public abstract Print(): void;
}
class ProductComponent extends ProductTemplate
{
Name = "Samsung TV";
Price = 45000.44;
Qty = 2;
Total(){
return this. Qty * this. Price;
}
Print(){
console.log(`Name=${this.Name}\nPrice=${this.Price}\nQty=${this.Qty}\nTotal=${t
his.Total()}`);
}
}
Generics
- Generic refers to type safe content with strongly typed nature.
- A generic type is open to handle any type until the value is provided.
- A generic type and make the component as strongly typed after the value is assigned.
- TypeScript can have various Generic members,
a) Method can be generic
b) Property can be generic
c) Parameter can be generic
d) Class can be generic
Syntax:
public Print<T>(a: T, b:T)
{
console.log(`a=${a}\n b=${b}`);
}
Print<number>(10, 20);
Print<string>("A", "B");
Ex-1:
Page 36 of 42
interface IProduct
{
Name: string;
Price: number;
}
interface IEmployee
{
FirstName: string;
Designation: string;
Salary: number;
}
class Service
{
public GetData<T>(data: T){
for(var property in data){
console.log(`${property} : ${data[property]}`);
}
}
}
let obj = new Service();
console.log(`----Employee Details----`);
obj. GetData<IEmployee>({FirstName: "John", Designation: "Manager", Salary: 50000});
console.log(`----Product Details-----`);
obj. GetData<IProduct>({Name: "TV", Price: 45000});
Ex-2:
interface IOracle
{
UserName: string;
Password: string;
Database: string;
}
interface IMySql
{
Host: string;
User: string;
Pwd: string;
Db: string;
}
interface IMongoDB
{
Url:string;
}
class Database<T>
{
public ConnectionString: T| null = null;
public Connect():void{
for(var property in this. ConnectionString) {
console.log(`${property}: ${this. ConnectionString[property]}`);
}
}
Page 37 of 42
}
console.log(`------Oracle Connection---------`);
let oracle = new Database<IOracle>();
oracle. ConnectionString = {
UserName: "scott",
Password: "tiger",
Database: "studentsDb"
}
oracle. Connect();
console.log(`------MySql Connection---------`);
let mysql = new Database<IMySql>();
mysql.ConnectionString = {
Host: "localhost",
User: "root",
Pwd: "12345",
Db: "EmpDb"
}
mysql.Connect();
console.log(`------MongoDB Connection--------`);
let mongo = new Database<IMongoDB>();
mongo. ConnectionString = {
Url: "mongodb://127.0.0.1:27017"
}
mongo. Connect();
Enum
- Enum refers to Enumeration, which is a set of constants.
- Every constant must be initialized.
- Enum in TypeScript can have following constants
a) string
b) number
c) expression
- Enum number constants can have auto implementation.
- Auto implementation is not supported for string and expression.
Syntax:
enum Name
{
ref = value
}
Name. ref
Ex-1:
enum ErrorCodes
{
OK,
Success=201,
NotFound = 404,
InternalError
Page 38 of 42
}
console.log(`Status Code for Success : ${ErrorCodes. Success}`);
Ex-2:
enum ErrorCodes
{
A = 10,
B = 20,
C=A+B
}
console.log(`Addition=${ErrorCodes. C}`);
- Enum supports reverse mapping. It allows to access a key with reference of value.
Ex-3:
enum ErrorCodes
{
NotFound = 404
}
console.log(`${ErrorCodes. NotFound}: ${ErrorCodes[404]}`);
Modules
- Module is a set of variables, functions, classes, contracts, templates etc.
- Modules are used to build a library for application.
- JavaScript requires various module systems to handle modules.
- The popular module systems are
Common JS
Require JS
UMD [Universal Module Distribution]
AMD [Asynchronous Module Distribution] etc..
Note: You view or change the current module system in your project
go to "tsconfig.json"
NPM installs a module system called common js.
Page 39 of 42
Syntax:
export default interface Name { }
Note: Only one member can be marked as default. There can't be multiple defaults in a
module. If we want to automatically load members into memory then mark it as default.
- The members of any module can be accessed and used in another module by importing
into context.
Syntax:
import {MemberName} from "ModuleName";
import {IProductContract} from "ProductContract";
- We can import both default and non-default members, but the default member can't be
last.
Syntax:
import Default_Member, {MemberName} from "ModuleName";
Ex:
1. Add following folders into "library" folder
contracts
templates
component
Page 40 of 42
public Qty: number = 0;
public CategoryName: string = "";
public abstract Total(): number;
public abstract Print(): void;
}
6. Compile Index.ts
1. Demo.js
export function Hello(){
return "Hello ! Welcome to Modules in JavaScript";
}
export function Addition(a,b) {
return a + b;
}
2. Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
Page 41 of 42
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="module">
import {Hello, Addition} from "../library/demo.js";
document.querySelector("p").innerHTML = Hello() + "<br>" + "Addition=" +
Addition(20,30);
</script>
</head>
<body>
<p></p>
</body>
</html>
Page 42 of 42