[go: up one dir, main page]

0% found this document useful (0 votes)
8 views63 pages

WEBX Module2

This document provides an overview of TypeScript, including its environment setup, types, variables, operators, decision-making structures, and functions. It explains how to install Node.js and Visual Studio Code, compile TypeScript code, and outlines the different data types and variable scopes in TypeScript. Additionally, it covers the syntax for functions, including named and anonymous functions, as well as the use of parameters and their types.

Uploaded by

leken52079
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views63 pages

WEBX Module2

This document provides an overview of TypeScript, including its environment setup, types, variables, operators, decision-making structures, and functions. It explains how to install Node.js and Visual Studio Code, compile TypeScript code, and outlines the different data types and variable scopes in TypeScript. Additionally, it covers the syntax for functions, including named and anonymous functions, as well as the use of parameters and their types.

Uploaded by

leken52079
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Module II

Type Script

-Pragati Patil
CO2: Apply strict type rules by use of typescript

Contents:
 Overview
 JavaScript VS Typescript
 TypeScript Environment setup
 TypeScript Types
 Variables and operators
 Decision making and loops
 TypeScript Functions
 TypeScript Classes and Objects
 TypeScript Modules
 TypeScript Internal Architecture
Example:
Typescript Environment setup
 The source files are typically named with the extension .ts

 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


#Step 1.Installing Node.js
 Node.js is an open source, cross-platform runtime environment for server-side JavaScript.
 Node.js is required to run JavaScript without a browser support. It uses Google V8 JavaScript
engine to execute code.
 You may download Node.js source code or a pre-built installer for your platform. Node is
available here − https://nodejs.org/en/download
Installation on Windows:
➢ 1 - Download and run the .msi installer for Node.
➢ 2 − To verify if the installation was successful, enter the command node –v in the terminal
window.

➢ 3 − Type the following command in the terminal window to install TypeScript.


#Step 2.Installing Visual studio as IDE support
 This is an open-source IDE from Visual Studio.
 It is available for Mac OS X, Linux and Windows platforms.
 VScode is available at − https://code.visualstudio.com/
Installation on Windows
1 − Download Visual Studio Code for Windows.
Step 2 − Double-click on VSCodeSetup.exe to launch the setup process. This will only take
a minute.

Step 3 − A screenshot of the IDE is given below.


Step 4 − You may directly traverse to the file’s path by right clicking on the file → open in command prompt.
Similarly, the Reveal in Explorer option shows the file in the File Explorer.
Your First TypeScript Code
Let us start with the traditional “Hello World” example −

var message:string = "Hello World"


console.log(message)

 On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10


var message = "Hello World";
console.log(message);

#Line1 declares a variable by the name message. Variables are a mechanism to store values in a program.
#Line2 prints the variable’s value to the prompt. Here, console refers to the terminal window.
The function log () is used to display text on the screen.
# Compile and Execute a TypeScript Program

Compile and execute a TypeScript program using NOTE : If we directly run ".ts" file on the web browser,
Visual Studio Code. Follow the steps given below it will throw an error message. But after the
compilation of ".ts" file, we will get a ".js" file, which
• Step 1 − Save the file with .ts extension. can be executed on any browser.
• 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 , type the following in the terminal

node Test.js
# Typescript Types
 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.

Syntax:
[Keyword] [Variable Name]: [Data Type] = [Value];
[Keyword] [Variable Name]: [Data Type];
TypeScript Types
 We can classify the TypeScript data type as following:

fig. TypeScript Types


• 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/Primitive types
The table illustrates all the built-in types in TypeScript
Data type Keyword Description
Note:
Number number Double precision 64-bit floating point values. It can be However, null and undefined are not
used to represent both, integers and fractions.
the same.
A variable initialized with undefined
String string Represents a sequence of Unicode characters
means that the variable has no value
or object assigned to it
Boolean boolean Represents logical values, true and false While null means that the variable has
Void void Used on function return types to represent non- been set to an object whose value is
returning functions undefined.
Null null Represents an intentional absence of an object value.

Undefined undefined Denotes value given to all uninitialized variables

• User-defined Types
User-defined types include Enumerations (enums), classes, interfaces, arrays, and tuple.
#TypeScript - Variables

Variable is “a named space in the memory” that stores values


 TypeScript variables must follow the JavaScript naming rules −
1. Variable names can contain alphabets and numeric digits.
2. They cannot contain spaces and special characters, except the
underscore (_) and the dollar ($) sign.
3. Variable names cannot begin with a digit.
4. A variable must be declared before it is used.
5. Use the var keyword to declare variables.
Syntax to declare variables
S.No. Variable Declaration
Variable Declaration Syntax & Description

1. var name:string = ”mary”


The variable stores a value of type string

2. var name:string;
The variable is a string variable. The variable’s value is set to undefined by default

3. var name = ”mary”


The variable’s type is inferred from the data type of the value. Here, the variable is of the
type string

4. var name;
The variable’s data type is any. Its value is set to undefined by default.
TypeScript Variable Scope
The scope of a variable specifies where the variable is defined. The availability of a variable
within a program is determined by its scope.
TypeScript variables can be of the following scopes −
• Global Scope − Global variables are declared outside the programming constructs. These
variables can be accessed from anywhere within your code.
• Class Scope − These variables are also called fields. Fields or class variables are declared
within the class but outside the methods. These variables can be accessed using the object of
the class. Fields can also be static. Static fields can be accessed using the class name.
• Local Scope − Local variables, as the name suggests, are declared within the constructs like
methods, loops etc. Local variables are accessible only within the construct where they are
declared.
#TypeScript - Operators
The major operators in TypeScript can be classified as −
• Arithmetic operators
• Logical operators
• Relational operators
• Bitwise operators
• Assignment operators
• Ternary/conditional operator
• String operator
• Type Operator
Arithmetic Operators
Assume a=10, b=5
Operator Description Example
returns the sum of the operands a + b is 15
+ (Addition)

- (Subtraction) returns the difference of the values a - b is 5

* (Multiplication) returns the product of the values a * b is 50

/ (Division) performs division operation and returns the a / b is 2


quotient
% (Modulus) performs division operation and returns the a % b is 0
remainder
++ (Increment) Increments the value of the variable by one a++ is 11

-- (Decrement) Decrements the value of the variable by one a-- is 9


Relational Operators
Assume the value of A=10 and B=20

Operator Description Example

> Greater than (A > B) is False

< Lesser than (A < B) is True

>= Greater than or equal to (A >= B) is False

<= Lesser than or equal to (A <= B) is True

== Equality (A == B) is false

!= Not equal (A != B) is True


Logical Operators
Assume the value of variable A is 10 and B is 20.

Operator Description Example

The operator returns true only if all the (A > 10 && B > 10) is False
&& (And) expressions specified return true

|| (OR) The operator returns true if at least one (A > 10 || B >10) is True
of the expressions specified return true

! (NOT) The operator returns the inverse of the !(A >10 ) is True
expression’s result. For E.g.: !(>5)
returns false
Bitwise Operators
Assume variable A = 2 and B = 3
Operator Description Example
It performs a Boolean AND operation on each bit of its integer (A & B) is 2
& (Bitwise AND)
arguments.
| (BitWise OR) It performs a Boolean OR operation on each bit of its integer (A | B) is 3
arguments.
^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its (A ^ B) is 1
integer arguments. Exclusive OR means that either operand one is
true or operand two is true, but not both.

~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the (~B) is -4
operand.
<< (Left Shift) It moves all the bits in its first operand to the left by the number of (A << 1) is 4
places specified in the second operand. New bits are filled with
zeros. Shifting a value left by one position is equivalent to
multiplying it by 2, shifting two positions is equivalent to
multiplying by 4, and so on.

>> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved (A >> 1) is 1
right by the number of bits specified by the right operand.

>>> (Right shift with Zero) This operator is just like the >> operator, except that the bits (A >>> 1) is 1
shifted in on the left are always zero.
Assignment Operators
Operator Description Example
Assigns values from the right side operand to the C = A + B will assign the
= (Simple Assignment) left side operand value of A + B into C

+= (Add and It adds the right operand to the left operand and C += A is equivalent to C = C
Assignment) assigns the result to the left operand. +A

-= (Subtract and It subtracts the right operand from the left operand C -= A is equivalent to C = C
Assignment) and assigns the result to the left operand. -A

*= (Multiply and It multiplies the right operand with the left C *= A is equivalent to C = C
Assignment) operand and assigns the result to the left operand. *A

/= (Divide and It divides the left operand with the right operand
Assignment) and assigns the result to the left operand.
#Decision Making and loops
 Decision-making structures require that the programmer specifies one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.

S.No. Statement & Description


1. if statement
An ‘if’ statement consists of a Boolean expression followed by one or more
statements.
2. if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which
executes when the Boolean expression is false.
3. else…if and nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
4. switch statement
A ‘switch’ statement allows a variable to be tested against a list of values.
 A loop statement allows us to execute a statement or group of statements multiple times.
Given below is the general form of a loop statement in most of the programming
languages.
Example: while versus do..while

On compiling, it will generate following JavaScript code −


Break
Statement
Continue
Statement
# Typescript Functions
 Function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
Sr.No Funtions & Description

1. Defining a Function
A function definition specifies what and how a specific task would be done.

2. Calling a Function
A function must be called so as to execute it.

3. Returning Functions
Functions may also return value along with control, back to the caller.

4. Parameterized Function
Parameters are a mechanism to pass values to functions.
➢ Function Aspects
 Function declaration
Syntax:
function functionName( [arg1, arg2, ...argN] );
 Function definition
Syntax:
function functionName( [arg1, arg2, ...argN] ){
//code to be executed
}
 Function call
Syntax:
FunctionName();
➢ Function Creation
 We can create a function in two ways. These are:
1. Named Function
When we declare and call a function by its given name,
then this type of function is known as a named function.
Syntax:
functionName( [arguments] ) { }
Example:
//Function Definition
function display() {
console.log("Hello WebX.0!");
}
//Function Call
display();
Output:
Hello WebX.0!
2. Anonymous Function
 A function without a name is known as an anonymous function.
 These type of functions are dynamically declared at runtime.
Syntax:
let res = function( [arguments] ) { }
Example:
// Anonymous function
let myAdd = function (x: number, y: number) : number {
return x + y;
};
// Anonymous function call
console.log(myAdd(2,3));
Output:
5
Function Parameter
 Parameters are the values or arguments that passed to a function.
 In TypeScript, the compiler accepts the same number and type of arguments as defined in the
function signature.
 Function parameter can be categories into the following:
1. Optional Parameter
• In JavaScript, we can call a function without passing any arguments.
• Unlike JavaScript, the TypeScript compiler will throw an error if we try to invoke a function without providing the exact
number and types of parameters as declared in its function signature.
2. Default Parameter
• TypeScript provides an option to set default values to the function parameters.
• If the user does not pass a value to an argument, TypeScript initializes the default value for the parameter.
3. Rest Parameter
• The rest parameter is used to pass zero or more values to a function.
• We can declare it by prefixing the three "dot“ characters ('...') before the parameter.
• It allows the functions to have a different number of arguments without using the arguments object.
Syntax:
function function_name(parameter1[:type], parameter2[:type],
...parameter[:type]) { }
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. The syntax to declare a function with
optional parameter is as given below −

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


Rest parameters
 Rest parameters are similar to variable arguments in Java. 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. When the number of parameters that a function will receive is not known or can vary, we
can use rest parameters.

 To declare a rest parameter, the parameter name is prefixed with three periods.
Any nonrest parameter should come before the rest parameter.
Default Parameters
 Function parameters can also be assigned values by default. However, such parameters
can also be explicitly passed values.
Syntax:
function function_name(param1[:type],param2[:type] = default_value) { }
*Note − A parameter cannot be declared optional and default at the same time.
;

# 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.
Lambda Function - Anatomy
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
 Lambda Expression
It is an anonymous function expression that points to a single line of code. Its
syntax is as follows -
( [param1, parma2,…param n] )=>statement
#TypeScript classes and Objects
 TypeScript supports object-oriented programming features like classes, interfaces, etc.
 JavaScript ES5 or earlier didn’t support classes. Typescript gets this feature from ES6.
Creating classes:
Syntax:
Creating Instance objects
Syntax:
Class Inheritance
Syntax:
class child_class_name extends parent_class_name
 Inheritance can be classified as −
• Single − Every class can at the most extend from one parent class
• Multiple − A class can inherit from multiple classes. TypeScript doesn’t support multiple
inheritance.
• Multi-level − One class inherits the features from a parent class and the newly created sub-
class becomes the base class for another new class.
➢ Data Hiding
S.No. Access Specifier & Description
1. public
A public data member has universal accessibility. Data members in a class are public by
default.

2. private
Private data members are accessible only within the class that defines these members. If an
external class member tries to access a private member, the compiler throws an error.

3. protected
A protected data member is accessible by the members within the same class as that of the
former and also by the members of the child classes.
#Typescript Modules
 A module is designed with the idea to organize code written in TypeScript. Modules are broadly divided into −
• Internal Modules
• External Modules

➢ Internal modules were in the earlier version of Typescript.


• It was used for logical grouping of the classes, interfaces, functions, variables into a single unit and
can be exported in another module.
➢ The modules are named as a namespace in the latest version of TypeScript. So today, internal modules are obsolete . But
they are still supported by using namespace over internal modules.
Internal Module Syntax in Earlier Version: Internal Module Syntax from ECMAScript 2015:
External module:
 External modules are also known as a module.
 When the applications consisting of hundreds of files, then it is almost impossible to handle
these files without a modular approach.
 External Module is used to specify the load dependencies between the multiple external js
files.
 If the application has only one js file, the external module is not relevant.
 ECMAScript 2015(ES6) module system treats every file as a module.
 We can use the declare module in other files by using an import keyword, which looks like
below.
 The file/module name is specified without an extension.
import { class/interface name } from 'module_name';
Example:
R
E
C
A
P
R
E
C
A
P
R
E
C
A
P
R
E
C
A
P
Typescript Internal Architecture
University Questions:
❖ Typescript v/s Javascript. 5
❖ Explain an arrow function in Typescript. 5
❖ Explain Modules in Typescript with example 10
❖ Explain Multilevel Inheritance in Typescript with suitable example. 5
❖ Differentiate Var v/s Let. In addition ,Explain function overloading with
suitable example. 10

You might also like