paidiblog825102560.files.wordpress.com€¦  · web viewrest parameters don’t restrict the...

45
3.1. Introduction: Why TypeScript is developed while having JavaScript? When JavaScript was developed then JavaScript development team introduced JavaScript as a client-side programming language. But when people was using JavaScript then developer get to know that JavaScript can be used as a server-side programming language also. But When JavaScript was growing then the code of JavaScript became complex and heavy. Because of this, JavaScript was even not able to full fill the requirement of Object-oriented programming language. This prevents JavaScript from succeeding at the enterprise level as a server-side technology. Then TypeScript was developed by the development team to bridge this gap. 3.1.1 What is Typescript? By definition, “TypeScript is JavaScript for application-scale development.” TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features. 3.1.2 Features of TypeScript: TypeScript Code is converted into Plain JavaScript Code:: TypeScript code is not understandable by the browsers. That’s why if the code is written in TypeScript then it is compiled and converted the code i.e. translate the code into JavaScript. The above process is known as Trans-piled. By the help of JavaScript code, browsers are able to read the code and display.

Upload: others

Post on 18-Jun-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

3.1. Introduction:

Why TypeScript is developed while having JavaScript?

When JavaScript was developed then JavaScript development team introduced JavaScript as a client-side programming language. But when people was using JavaScript then developer get to know that JavaScript can be used as a server-side programming language also. But When JavaScript was growing then the code of JavaScript became complex and heavy. Because of this, JavaScript was even not able to full fill the requirement of Object-oriented programming language. This prevents JavaScript from succeeding at the enterprise level as a server-side technology. Then TypeScript was developed by the development team to bridge this gap.

3.1.1 What is Typescript?

By definition, “TypeScript is JavaScript for application-scale development.”

TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft. TypeScript is both a language and a set of tools. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features.

3.1.2 Features of TypeScript:

TypeScript Code is converted into Plain JavaScript Code:: TypeScript code is not understandable by the browsers. That’s why if the code is written in TypeScript then it is compiled and converted the code i.e. translate the code into JavaScript. The above process is known as Trans-piled. By the help of JavaScript code, browsers are able to read the code and display.

JavaScript is TypeScript: Whatever code is written in JavaScript can be converted to TypeScript by changing the extension from .js to .ts.

Use TypeScript anywhere: TypeScript code can be run on any browser, devices or in any operating system. TypeScipt is not specific to any Virtual-machine etc.

TypeScript supports JS libraries: With TypeScript, developers can use existing JavaScript code, incorporate popular JavaScript libraries, and can be called from other JavaScript code.

Difference between TypeScript and JavaScript:

TypesScript is known as Object oriented programming language whereas JavaScript is a scripting language.

TypeScript has a feature known as Static typing but JavaScript does not have this feature. TypeScript gives support for modules whereas JavaScript does not support modules. TypeScript has Interface but JavaScript does not have Interface.

Page 2: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

TypeScript support optional parameter function but JavaScript does not support optional parameter function.

Advantages of using TypeScript over JavaScript

TypeScript always point out the compilation errors at the time of development only. Because of this at the run-time the chance of getting errors are very less whereas JavaScript is an interpreted language.

TypeScript has a feature which is strongly-typed or supports static typing. That means Static typing allows for checking type correctness at compile time. This is not available in JavaScript.

TypeScript is nothing but JavaScript and some additional features i.e. ES6 features. It may not be supported in your target browser but TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 also.

Disadvantages of using TypeScript over JavaScript

Generally TypeScript takes time to compile the code. TypeScript does not support abstract classes.

Typescript is an Open Source technology. It can run on any browser, any host, and any OS. You will need the following tools to write and test a Typescript program −

(i)A Text Editor

The text editor helps you to write your source code. Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors used may vary with Operating Systems.

The source files are typically named with the extension .ts

Page 3: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

(ii) The TypeScript Compiler

The TypeScript compiler is itself a .ts file compiled down to JavaScript (.js) file. The TSC (TypeScript Compiler) is a source-to-source compiler (transcompiler / transpiler).

The TSC generates a JavaScript version of the .ts file passed to it. In other words, the TSC produces an equivalent JavaScript source code from the Typescript file given as an input to it. This process is termed as transpilation.

However, the compiler rejects any raw JavaScript file passed to it. The compiler deals with only .ts or .d.ts files.

3.2 Compile and Execute a TypeScript Program

Let us see how to compile and execute a TypeScript program using Visual Studio Code. Follow the steps given below −

Step 1 − 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.

Page 4: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

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

3.3.tsconfig.json

The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled in one of the following ways:

Using tsconfig.json

By invoking tsc with no input files, in which case the compiler searches for the tsconfig.json file starting in the current directory and continuing up the parent directory chain.

By invoking tsc with no input files and a --project (or just -p) command line option that specifies the path of a directory containing a tsconfig.json file, or a path to a valid .json file containing the configurations.

When input files are specified on the command line, tsconfig.json files are ignored.

3.4 Compiler Flags(Compiler Options)

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.

The following table lists some common flags associated with the TSC compiler. A typical command-line usage uses some or all switches.

S.No. Compiler flag & Description

1. --help : Displays the help manual

2. --module: Load external modules

3. --target: Set the target ECMA version

4. --declaration: Generates an additional .d.ts file

5. --removeComments: Removes all comments from the output file

Page 5: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

6. --out: Compile multiple files into a single output file

7. --sourcemap: Generate a sourcemap (.map) files

8. --module noImplicitAny: Disallows the compiler from inferring the any type

9. --watch: Watch for file changes and recompile them on the fly

3.5 Building blocks of Typescript

A TypeScript program is composed of −

Modules Functions Variables Statements and Expressions Comments

The Type System represents the different types of values supported by the language. The Type System checks the validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. The Type System further allows for richer code hinting and automated documentation too.

3.5.1 Data types

TypeScript provides data types as a part of its optional Type System. The data type classification is as given below −

Page 6: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

The Any type

The any data type is the super type of all types in TypeScript. It denotes a dynamic type. Using the any type is equivalent to opting out of type checking for a variable.

Built-in types

The following table illustrates all the built-in types in TypeScript −

Data type Keyword Description

Number NumberDouble precision 64-bit floating point values. It can be used to represent both, integers and fractions.

String string Represents a sequence of Unicode characters

Boolean boolean Represents logical values, true and false

Void void Used on function return types to represent non-returning functions

Null null Represents an intentional absence of an object value.

Undefined undefined Denotes value given to all uninitialized variables

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.Ex: Var name:string =”cvr”

Page 7: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Var name=”cvr”Var name

Var name:string

3.5.2 Operators:

The major operators in TypeScript can be classified as −

Arithmetic operators : +,-,*,/,%(Modulus),++,-- Relational operators : <,>,<=,>=,==,!= Logical operators : &&(AND), ||(OR),!(NOT) Bitwise operators : &(Bitwise AND), |, ^,~, <<,>>, >>> (Right shift with Zero) Assignment operators : =, +=, -+,/+.*= Ternary/conditional operator : ?: (Test ? expr1 : expr2) String operator : Concatenation operator (+) Type Operator : typeof. It is a unary operator. This operator returns the data type of the

operand

Ex: var num = 12 console.log(typeof num); //output: number

3.5.3 Control Structures:

1.Decision Making Statements :S.No. Statement & Description

1.

if statement An ‘if’ statement consists of a Boolean expression followed by one or more statements. if(boolean_expression) { // statement(s) will execute if the boolean expression is true }

2. if...else statement

An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the Boolean expression is false.

if(boolean_expression) { // statement(s) will execute if the boolean expression is true} else { // statement(s) will execute if the boolean expression is false }

Page 8: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

3.

else…if and nested if statements

You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).

if (boolean_expression1) { //statements if the expression1 evaluates to true } else if (boolean_expression2) { //statements if the expression2 evaluates to true } else { //statements if both expression1 and expression2 result to false }

4.

switch statement

A ‘switch’ statement allows a variable to be tested against a list of values.

switch(variable_expression) { case constant_expr1: { //statements; break; } case constant_expr2: { //statements; break; } default: { //statements; break; } }

2. Loops

a. for loop : The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as below −

Syntax

Page 9: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

for (initial_count_value; termination-condition; step) {//statements }

b. while loop : The while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed.

Syntax:

while(condition) { // statements if the condition is true

}

c. do-while loop : The do…while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes. However, the condition is evaluated for the subsequent iterations. In other words, the code block will be executed at least once in a do…while loop.

Syntax: do {

//statements } while(condition)

3. break : The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Its syntax is as follows −

Syntaxbreak

4. continue : The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue doesn’t exit the loop. It terminates the current iteration and starts the subsequent iteration.

Syntaxcontinue

3.6 Functions

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks

Page 10: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read

and maintain the program’s code.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

function function_name(param1 [:datatype], ( param2 [:datatype]):return_type {

// function body return value;

}

Types of Parameters: Optional Parameters : Optional parameters can be used when arguments need not be

compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function.

function function_name (param1[:type], param2[:type], param3[:type]){}

Rest Parameters : Rest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all be of the same type. In other words, rest parameters act as placeholders for multiple arguments of the same type. To declare a rest parameter, the parameter name is prefixed with three periods. Any nonrest parameter should come before the rest parameter.

function function_name (param1[:type], param2[:type],… param3[:type[]]){ }

Default Parameters: Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.

function function_name(param1[:type],param2[:type] = default_value) { }

3.6.2 Lambda Functions

Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.

Page 11: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Lambda Function – Anatomy( [param1, parma2,…param n] )=>statement;

There are 3 parts to a Lambda function −

Parameters − A function may optionally have parameters The fat arrow notation/lambda notation (=>) − It is also called as the goes to operator Statements − represent the function’s instruction set

Ex:Var f =(x)=>x*xconsole.log(f(10))

3.6.3 Function Overloads

Functions have the capability to operate differently on the basis of the input provided to them. In other words, a program can have multiple methods with the same name with different implementation. This mechanism is termed as Function Overloading. TypeScript provides support for function overloading.

To overload a function in TypeScript, you need to follow the steps given below −

Step 1 − Declare multiple functions with the same name but different function signature. Function signature includes the following.

The data type of the parameter

function disp(string):void; function disp(number):void;

The number of parameters

function disp(n1:number):void; function disp(x:number,y:number):void;

The sequence of parameters

function disp(n1:number,s1:string):void; function disp(s:string,n:number):void;

Note − The function signature doesn’t include the function’s return type.

Step 2 − The declaration must be followed by the function definition. The parameter types should be set to any if the parameter types differ during overload. Additionally, for case b

Page 12: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

explained above, you may consider marking one or more parameters as optional during the function definition.

Step 3 − Finally, you must invoke the function to make it functional.

Example

Let us now take a look at the following example code −

function disp(s1:string):void; function disp(n1:number,s1:string):void;

function disp(x:any,y?:any):void { console.log(x); console.log(y); } disp("abc") disp(1,"xyz");

The first two lines depict the function overload declaration. The function has two overloads −

o Function that accepts a single string parameter.o Function that accepts two values of type number and string respectively.

The third line defines the function. The data type of the parameters are set to any. Moreover, the second parameter is optional here.

The overloaded function is invoked by the last two statements.

On compiling, it will generate following JavaScript code −

//Generated by typescript 1.8.10function disp(x, y) { console.log(x); console.log(y);}disp("abc");disp(1, "xyz");

3.7.TypeScript - Class

In object-oriented programming languages like Java and C#, classes are the fundamental entities used to create reusable components. Functionalities are passed down to classes and objects are created from classes. However, until ECMAScript 6 (also known as ECMAScript 2015), this was not the case with JavaScript. JavaScript has been primarily a functional programming language where inheritance is prototype-based. Functions are used to build reusable components. In ECMAScript 6, object-oriented class based approach was introduced. TypeScript introduced classes to avail the benefit of object-oriented techniques like encapsulation and abstraction. The

Page 13: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

class in TypeScript is compiled to plain JavaScript functions by the TypeScript compiler to work across platforms and browsers.

A class can include the following:

Constructor Properties Methods

The following is an example of a class in TypeScript:

Example: Class

class Employee { empCode: number; empName: string;

constructor(code: number, name: string) { this.empName = name; this.empCode = code; }

getSalary() : number { return 10000; }}

The TypeScript compiler will convert the above class to the following JavaScript code using closure:

var Employee = /** @class */ (function () { function Employee(name, code) { this.empName = name; this.empCode = code; } Employee.prototype.getSalary = function () { return 10000; }; return Employee;}());

Constructor

The constructor is a special type of method which is called when creating an object. In TypeScript, the constructor method is always defined with the name "constructor".

Example: Constructor

class Employee {

Page 14: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

empCode: number; empName: string; constructor(empcode: number, name: string ) { this.empCode = empcode; this.name = name; }}

3.8 Modules Modules helps you segmenting your application. Indeed, modules allows you to create small units of independent and reusable code. Plus, modules know their dependencies, so they can load them when needed in the right order

In TypeScript, a module is a file containing values, functions or classes. You can make some of them public, i.e. visible from other modules, by exporting them. Non exported objects are private.

Page 15: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms . Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms .

Exporting a declarationAny declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.

Shape.ts

class shape {

function draw(){ console.log(“Inside shape” } }export shape

main.ts

import shape

class main {

}

3.9. Inheritance

Just like object-oriented languages such as Java and C#, TypeScript classes can be extended to create new classes with inheritance, using the keyword extends.

Example: Inheritance

class Person { name: string; constructor(name: string) { this.name = name; }}

Page 16: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

class Employee extends Person { empCode: number; constructor(empcode: number, name:string) { super(name); this.empCode = empcode; } displayName():void { console.log("Name = " + this.name + ", Employee Code = " + this.empCode); }}

let emp = new Employee(100, "Bill");emp.displayName(); // Name = Bill, Employee Code = 100

The constructor of the Employee class initializes its own members as well as the parent class's properties using a special keyword 'super'. The super keyword is used to call the parent constructor and passes the property values.

3.9.1 TypeScript - Interface

Interface is a structure that defines the contract in your application. It defines the syntax for classes to follow. Classes that are derived from an interface must follow the structure provided by their interface.

The TypeScript compiler does not convert interface to JavaScript. It uses interface for type checking. This is also known as "duck typing" or "structural subtyping".One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.

Example: Interface

interface IEmployee { empCode: number; empName: string; getSalary: (number) => number; // arrow function getManagerName(number): string; }

Page 17: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

interface IPerson { firstName:string, lastName:string, sayHi: ()=>string }

var customer:IPerson = { firstName:"Ajay", lastName:"Laddha", sayHi: ():string =>{return "Hi"} }

console.log("Customer Object Details: ");console.log(customer.sayHi()); console.log(customer.firstName); console.log(customer.lastName);

var employee:IPerson = { firstName:"Vikas", lastName:"Jainer", sayHi: ():string =>{return "Hello"} } console.log("Employee Object Details: ");console.log(employee.sayHi());console.log(employee.firstName);console.log(employee.lastName);

Interfaces have zero runtime JS impact. There is a lot of power in TypeScript interfaces to declare the structure of variables.

The following two are equivalent declarations, the first uses an inline annotation, the second uses an interface:

// Sample Adeclare var myPoint: { x: number; y: number; };

// Sample Binterface Point { x: number; y: number;}declare var myPoint: Point;

Page 18: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

3.10 GenericsWith generics, TypeScript enables you to write code that can act on a variety of data types instead of being limited to a single one.Generics offer a way to create reusable components. Generics provide a way to make components work with any data type and not restrict to one data type. So, components can be called or used with a variety of data types.

While using any is certainly generic in that it will cause the function to accept any and all types for the type of arg, we actually are losing the information about what that type was when the function returns. If we passed in a number, the only information we have is that any type could be returned.

Generics uses the type variable <T>, a special kind of variable that denotes types. The type variable remembers the type that the user provides and works with that particular type only. This is called preserving the type information.

function identity<T>(arg: T): T { return arg;}

The type variable T is also used to specify the type of the arguments and the return value. This means that the data type which will be specified at the time of a function call, will also be the data type of the arguments and of the return value.

Generic classes have a generic type parameter list in angle brackets (<>) following the name of the class.

class GenericNumber<T> { zeroValue: T; add: (x: T, y: T) => T;}

let myGenericNumber = new GenericNumber<number>();myGenericNumber.zeroValue = 0;myGenericNumber.add = function(x, y) { return x + y; };

3.11 Decorators :

With the introduction of Classes in TypeScript and ES6, there now exist certain scenarios that require additional features to support annotating or modifying classes and class members. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.

It serves the purpose of adding metadata to the existing code in a declarative way.

Page 19: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Types of decorators and its priority of execution are

1. Class decorator2. Method Decorator3. Accessor or Property Decorator4. Parameter Decorator 

1. Class decorator:

A Class Decorator is declared just before a class declaration. The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.

The expression for the class decorator will be called as a function at runtime, with the constructor of the decorated class as its only argument.

If the class decorator returns a value, it will replace the class declaration with the provided constructor function.

The following is an example of a class decorator (@sealed) applied to the Greeter class:

@sealedclass Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; }}

We can define the @sealed decorator using the following function declaration:

function sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype);}

When @sealed is executed, it will seal both the constructor and its prototype.

2. Method decorators:

A Method Decorator is declared just before a method declaration. The decorator is applied to the Property Descriptor for the method, and can be used to observe, modify, or replace a method definition.

The expression for the method decorator will be called as a function at runtime, with the following three arguments:

Page 20: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

1. Either the constructor function of the class for a static member, or the prototype of the class for an instance member.

2. The name of the member.3. The Property Descriptor for the member.

If the method decorator returns a value, it will be used as the Property Descriptor for the method.

The following is an example of a method decorator (@enumerable) applied to a method on the Greeter class:

class Greeter { greeting: string; constructor(message: string) { this.greeting = message; }

@enumerable(false) greet() { return "Hello, " + this.greeting; }}

We can define the @enumerable decorator using the following function declaration:

function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.enumerable = value; };}

The @enumerable(false) decorator here is a decorator factory. When the @enumerable(false) decorator is called, it modifies the enumerable property of the property descriptor.

3. Property Decorators

A Property Decorator is declared just before a property declaration. Property decorators are similar to method decorators. The only difference is they do not accept property descriptor as argument and do not return anything.

The expression for the property decorator will be called as a function at runtime, with the following two arguments:

1. Either the constructor function of the class for a static member, or the prototype of the class for an instance member.

2. The name of the member.

Page 21: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

const log = (target: Object, key: string | symbol) => {    let value = target[key];     const getter = () =>  {        console.log("Getting value: ", value);        return value;    };    const setter = (val) => {        console.log("Setting value: ", val);        value = val;    }    Reflect.deleteProperty[key];    Reflect.defineProperty(target, key, {        get: getter,        set: setter    });} class Box<T> {    @log    item: T;} const numberInABox = new Box<number>();numberInABox.item = 12;numberInABox.item; //Setting value: 12//Getting value: 12

The log decorator above redefines the decorated property on the object.

4. Parameter DecoratorsA Parameter Decorator is declared just before a parameter declaration. The parameter decorator is applied to the function for a class constructor or method declaration.

The expression for the parameter decorator will be called as a function at runtime, with the following three arguments:

1. Either the constructor function of the class for a static member, or the prototype of the class for an instance member.

2. The name of the member.3. The ordinal index of the parameter in the function’s parameter list.

Page 22: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

function logParameter(target: Object, propertyName: string, index: number) {

// generate metadatakey for the respective method // to hold the position of the decorated parameters const metadataKey = `log_${propertyName}_parameters`; if (Array.isArray(target[metadataKey])) { target[metadataKey].push(index); } else { target[metadataKey] = [index]; }}

class Employee { greet(@logParameter message: string): string { return `hello ${message}`; }}const emp = new Employee();emp.greet('hello');

In the code above, we collect all the index or position of the decorated parameters of the methods as metadata and attached to the prototype of the object.

Node.js

Introduction

Node.js is a very powerful JavaScript-based framework/platform built on Google Chrome's JavaScript V8 Engine.

It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications.

Node.js is open source, completely free, and used by thousands of developers around the world

Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine).

Node.js was developed by Ryan Dahl in 2009. Node.js is a platform built on Chrome's JavaScript runtime for easily

building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it

lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Page 23: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.

Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent.

Features of Node.js

Following are some of the important features that make Node.js the first choice of software architects.

Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.

Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.

Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.

No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks.

Application and companies which are using Node.js.

This list includes eBay, General Electric, GoDaddy, Microsoft, PayPal, Uber, LinkedIn,Wikipins, Yahoo!, and Yammer to name a few.

Following are the areas where Node.js is proving itself as a perfect technology partner.

I/O bound Applications

Page 24: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Data Streaming Applications Data Intensive Real-time Applications (DIRT) JSON APIs based Applications Single Page Applications

Note:- The only scenario where it should not be used is if there are long processing times which is required by the application.

Node is structured to be single threaded. If any application is required to carry out some long running calculations in the background. So if the server is doing some calculation, it won't be able to process any other requests. Node.js is best when processing needs less dedicated CPU time.

2 Environment Setup

To set up environment for Node.js, the following two softwares are required:

(a) Text Editor and

(b) The Node.js binary installables.

Text Editor

This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.

Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.

The files you create with your editor are called source files and contain program source code. The source files for Node.js programs are typically named with the extension ".js".

Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, and finally execute it.

The Node.js Runtime

Page 25: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

The source code written in source file is simply javascript. The Node.js interpreter will be used to interpret and execute your javascript code.

Node.js distribution comes as a binary installable for SunOS , Linux, Mac OS X, and Windows operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures.

A Node.js application consists of the following three important components −

Import required modules − We use the require directive to load Node.js modules.

Create server − A server which will listen to client's requests similar to Apache HTTP Server.

Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.

var http = require('http');

http.createServer(function (req, res) {    res.writeHead(200, {'Content-Type': 'text/html'});    res.end('<b>Hello World!<b>1');}).listen(8080);

Page 26: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

3 Node.js Console - REPL

Node.js comes with virtual environment called REPL. REPL stands for Read-Eval-Print-Loop. It is a quick and easy way to test simple Node.js/JavaScript code.

To launch the REPL (Node shell), open command prompt (in Windows) or terminal (in Mac or UNIX/Linux) and type node. It will change the prompt to > in Windows .

Node.js or Node comes bundled with a REPL environment. It performs the following tasks −

Read − Reads user's input, parses the input into JavaScript data-structure, and stores in memory.

Eval − Takes and evaluates the data structure. Print − Prints the result. Loop − Loops the above command until the user presses ctrl-c twice.

REPL can be started by simply running node on shell/console without any arguments as follows.:

>node

Simple ExpressionYou can execute various mathematical operations on REPL Node.js command prompt:

> node> 1 + 34> 1 + ( 2 * 3 ) - 43>Use Variables

You can make use variables to store values and print later like any conventional script. If var keyword is not used, then the value is stored in the variable and printed. Whereas if var keyword is used, then the value is stored but not printed. You can print variables using console.log().

Page 27: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

> node> x = 1010> var y = 10undefined> x + y20> console.log("Hello World")Hello Worldundefined

Multiline Expression

Node REPL supports multiline expression similar to JavaScript.

> node> var x = 0undefined> do {... x++;... console.log("x: " + x);... } while ( x < 5 );x: 1x: 2x: 3x: 4x: 5undefined>

... comes automatically when you press Enter after the opening bracket. Node automatically checks the continuity of expressions.

Underscore VariableUse underscore (_) to get the last result −$ node> var x = 10undefined> var y = 20undefined

Page 28: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

> x + y30> var sum = _undefined> console.log(sum)30undefined

Page 29: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Node.js REPL Commands

Commands Descriptionctrl + c It is used to terminate the current command.ctrl + c twice It terminates the node repl.ctrl + d It terminates the node repl.up/down keys It is used to see command history and modify previous commands.tab keys It specifies the list of current command..help It specifies the list of all commands..break It is used to exit from multi-line expressions..clear It is used to exit from multi-line expressions..save filename It saves current node repl session to a file..load filename It is used to load file content in current node repl session.

4 Node.js Package Manager(npm)

Node Package Manager provides two main functionalities:

It provides online repositories for node.js packages/modules which are searchable on search.nodejs.org

It also provides command line utility to install Node.js packages, do version management and dependency management of Node.js packages.

The npm comes bundled with Node.js installables in versions after that v0.6.3.

Installing Modules using NPM

There is a simple syntax to install any Node.js module −

> npm install <Module Name>

For example, following is the command to install a famous Node.js web framework module called express −

> npm install express

Page 30: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

Now you can use this module in your js file as following −

var express = require('express');

Page 31: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

5 Callback

Callbacks in the general definition are just functions that you pass to other functions. It is called at the completion of certain task.

Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are written in such a way that they support callbacks.

Blocking Code Example:

Create a text file named input.txt Create a js file named main.js with the following code −

var fs = require("fs");

var data = fs.readFileSync('input.txt');

console.log(data.toString());console.log("Program Ended");

Now run the main.js to see the result −

> node main.js

Non-Blocking Code Example:

Create a text file named input.txt Create main.js to have the following code −

var fs = require("fs");

fs.readFile('input.txt', function (err, data) { if (err) return console.error(err); console.log(data.toString());});

Page 32: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

console.log("Program Ended");

Now run the main.js to see the result –

> node main.js

Verify the Output.

Program EndedThen the contents of the file will be printedTutorials Point is giving self learning contentto teach the world in simple and easy way!!!!!

Thus, a blocking program executes very much in sequence. From the programming point of view, it is easier to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, it should be kept within the same block to make it sequential execution.

A function in NodeJS is either synchronous or asynchronous. An asynchronous function is a function which has the functionality to call events when they complete the execution. The asynchronous function does not wait for any task to complete, it continues its execution with next instruction.

Callback function is a function which is called automatically after the completion of the execution of a time-intensive process. We can understand it by one example -  reading a text file using NodeJS. Here, we assume that the text file is big so the process of reading this file is time-consuming. So, if we are to take a normal synchronous function for reading this text file. If the file is big and takes 9-10 seconds to read this text file. Thus, this program goes into the awaited state during reading of the file. No other operation is executed during this time. This is executed at the next instruction. So, it is called synchronous method.

Now, we are to read this file using callback process or the asynchronous method, when the program is executing, the command for reading a file does not wait for this operation to complete but it continues its execution with the next instruction. So, the program does not go into waited state or block state. Ones the file reading is completed, it automatically calls the callback function and it prints this text file content. This type of method is called the asynchronous method.

Page 33: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all
Page 34: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

6 Events in Node.js

Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur.

In an event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected.

Although events look quite similar to callbacks, the difference lies in the fact that callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners .

EventEmitter Class

EventEmitter class lies in the events module. It is accessible via the following code −

// Import events modulevar events = require('events');

// Create an eventEmitter objectvar eventEmitter = new events.EventEmitter();

Page 35: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.

EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

Methods

S.No. Method & Description

1

addListener(event, listener)

Adds a listener at the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained.

2

on(event, listener)

Adds a listener at the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. Returns emitter, so calls can be chained.

3

once(event, listener)

Adds a one time listener to the event. This listener is invoked only the next time the event is fired, after which it is removed. Returns emitter, so calls can be chained.

4

removeListener(event, listener)

Removes a listener from the listener array for the specified event. Caution − It changes the array indices in the listener array behind the listener. removeListener will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified event, then removeListener must be called multiple times to remove each instance. Returns emitter, so calls can be chained.

5 removeAllListeners([event])

Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added elsewhere in the code, especially when it's

Page 36: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

on an emitter that you didn't create (e.g. sockets or file streams). Returns emitter, so calls can be chained.

6

setMaxListeners(n)

By default, EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.

7listeners(event)

Returns an array of listeners for the specified event.

8

emit(event, [arg1], [arg2], [...])

Execute each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false otherwise.

1. For creating a new event

var event=require(‘events’);var eventEmitter=new event.EventEmitter();

2. For assigning any function to events. So, when this event is fired, the function gets executed.

eventEmitter.on(‘eventName’,functionName);

3. For firing the events.

eventEmitter.emit(‘eventName’);

Example:

var event = require('events');  

var eventEmitter = new event.EventEmitter();  

Page 37: paidiblog825102560.files.wordpress.com€¦  · Web viewRest parameters don’t restrict the number of values that you can pass to a function. However, the values passed must all

console.log('Function started...');  

//  Add listener function for Sumof2Number event  

evetnEmitter.on('Sumof2Number', function(num1, num2) {  

    console.log('Sum of both Number : ' + (Number(num1) + Number(num2)));  

});  

//  Add listener function for Mulof2Number event  

eventEmitter.on('Mulof2Number', function(num1, num2) {  

    console.log('Multiplication of both Number : ' + (Number(num1) * Number(num2)));  

});  

//  Call or fire both event.  

evetnEmitter.emit('Sumof2Number', '10', '20');  

evetnEmitter.emit('Mulof2Number', '10', '20');  

console.log('Function Ended...');