WEBX Module2
WEBX Module2
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
#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
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:
• User-defined Types
User-defined types include Enumerations (enums), classes, interfaces, arrays, and tuple.
#TypeScript - Variables
2. var name:string;
The variable is a string variable. The variable’s value is set to undefined by default
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)
== Equality (A == B) is false
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.
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 −
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