Module 2 - TypeScript (1)
Module 2 - TypeScript (1)
Overview of TypeScript
• Open-source
• Object-oriented language
• Developed and maintained by Microsoft
• Licensed under Apache 2 license
• it’s just JavaScript, with static typing ie. Typed Javascript
• Typed superset of JavaScript that compiles to plain JavaScript using
Typescript Compiler which can run on any browser
• TypeScript uses the JavaScript syntaxs and adds additional
syntaxes for supporting Types
• TypeScript files use the .ts
• Official website: https://www.typescriptlang.org
• The TypeScript compiler is also implemented in TypeScript and can be
used with any browser or JavaScript engines like Node.js.
Why TypeScript?
• Catches errors at compile-time, so that you can fix it before you run
code.
tsc --v
node <filename.js>
OR in production
• Install Node.js and TypeScript compiler
To Use
Output: HelloWorld
TypeScript Features
1. Cross-Platform/ Portable
2. Object-Oriented Language
3. Static type-checking
• checking, ensuring that the data flowing through the program is of the correct kind
of data.
• Type checking cuts down on errors, sets the stage for better tooling, and allows
developers to map their programs at a higher level.
• In static typing, compiler enforces that values use the same type
let value = 5;
value = "hello"; // error: Type '"hello"' is not assignable to type 'number'.
Javascript Code
function add(x, y){
return x + y;
}
let result = add(input1.value, input2.value);
console.log(result); // result of concatenating strings
Typescript Code
function add(x: number, y: number):number {
return x + y;
}
let result = add(input1.value, input2.value);
// throws error
• JavaScript is dynamically typed. It offers flexibility but also creates many
problems.
• TypeScript adds an optional type system to JavaScript to solve these
problems.
•
function add(a: any, b: any): any {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
if (typeof a === 'string' && typeof b === 'string') {
return a.concat(b);
}
}
console.log(add(3,6));
console.log(add("Hello","TypeScript"));
• DOM Manipulation
• TypeScript can be used to manipulate the DOM for adding or
removing elements similar to JavaScript.
• ES 6 Features
JavaScript Vs TypeScript
Sr. No. JavaScript TypeScript
1. It doesn't support strongly typed or static typing. It supports strongly typed or static typing feature.
3. JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.
7. Example: Example:
<script> function addNumbers(a:number, b:number) {
function addNumbers(a, b) { return a + b;
return a + b; }
} var sum = addNumbers(15, 25);
var sum = addNumbers(15, 25); console.log('Sum of the numbers is: ' + sum);
document.write('Sum of the numbers is: ' + sum);
</script>
TypeScript Variables
We can declare a variable in one of the four ways:
• Declare type and value in a single statement
[keyword] [identifier] : [type-annotation] = value;
• Declare type without value. Then the variable will be set to
undefined.
[keyword] [identifier] : [type-annotation];
• Declare its value without type. Then the variable will be set to any.
[keyword] [identifier] = value;
• Declare without value and type. Then the variable will be set to any and
initialized with undefined.
[keyword] [identifier];
• Note:
• Keyword]: It’s a keyword of the variable either var, let or const to define the scope
and usage of variable.
• [Variable Name]: It’s a name of the variable to hold the values in our application.
• [Data Type]: It’s a type of data the variable can hold such as number, string,
boolean, etc.
• [Value]: Assigning a required value to the variable.
TypeScript Data Types
let uname: string = "Albert Einstein"; // string var uname = "Albert Einstein"; // string
var ulocation = "Germany"; // string
let ulocation: string = "Germany"; // string var age = 38; // number
var isSciencetist = true; // boolean
let age: number = 38; // number console.log("Name:" + uname);
console.log("Location:" + ulocation);
let isSciencetist: boolean = true; // boolean console.log("Age:" + age);
console.log("Name:" + uname); console.log("Is a Sciencetist:" +
isSciencetist);
console.log("Location:" + ulocation);
console.log("Age:" + age);
console.log("Is Doctorate:" + isSciencetist);
var Vs let keyword
Sr. Var let
No.
1. The var keyword was introduced with JavaScript. The let keyword was added in ES6 (ES 2015) version of
JavaScript.
2. It has global scope. It is limited to block scope.
3. It can be declared globally and can be accessed globally. It can be declared globally but cannot be accessed
globally.
4. Variable declared with var keyword can be re-declared Variable declared with let keyword can be updated but not
and updated in the same scope. re-declared.
Example:
function varGreeter(){ Example:
var a = 10; function varGreeter(){
var a = 20; //a is replaced let a = 10;
console.log(a); let a = 20; //SyntaxError:
} //Identifier 'a' has already been declared
varGreeter(); console.log(a);
}
varGreeter();
5. It is hoisted. It is not hoisted.
Example: Example:
{ {
console.log(c); // undefined. console.log(b); // ReferenceError:
//Due to hoisting //b is not defined
var c = 2; let b = 3;
} }
TypeScript Operators
• Arithmetic operators
• Comparison (Relational) operators
• Logical operators
• Bitwise operators
• Assignment operators
• Ternary/conditional operator
• Concatenation operator
• Advanced Type Operator
Arithmetic Operators
Operator Operator_Name Description Example
+ Addition It returns an addition of the values. let a = 10;
let b = 20;
let c = a + b;
console.log( c ); // Output 30
- Subtraction It returns the difference of the values. let a = 20;
let b = 10;
let c = a - b;
console.log( c ); // Output 10
* Multiplication It returns the product of the values. let a = 30;
let b = 20;
let c = a * b;
console.log( c ); // Output 600
/ Division It performs the division operation, and let a = 100;
returns the quotient. let b = 20;
let c = a / b;
console.log( c ); // Output 5
% Modulus It performs the division operation and let a = 75;
returns the remainder. let b = 20;
let c = a % b;
console.log( c ); // Output 15
++ Increment It is used to increments the value of the let a = 15;
variable by one. a++;
console.log( a ); // Output 16
-- Decrement It is used to decrements the value of the let a = 15;
variable by one. a--;
console.log( a ); // Output 14
Operator
Comparison (Relational) Operators
Operator_Name Description Example
== Is equal to It checks whether the values of the two operands are equal or not. let a = 10;
let b = 20;
console.log(a==b); //false
console.log(a==10); //true
console.log(10=='10'); //true
=== Identical(equal and of the same type) It checks whether the type and values of the two operands are equal or not. let a = 10;
let b = 20;
console.log(a===b); //false
console.log(a===10); //true
console.log(10==='10'); //false
!= Not equal to It checks whether the values of the two operands are equal or not. let a = 10;
let b = 20;
console.log(a!=b); //true
console.log(a!=10); //false
console.log(10!='10'); //false
!== Not identical It checks whether the type and values of the two operands are equal or not. let a = 10;
let b = 20;
console.log(a!==b); //true
console.log(a!==10); /false
console.log(10!=='10'); //true
> Greater than It checks whether the value of the left operands is greater than the value of the right operand or not. let a = 30;
let b = 20;
console.log(a>b); //true
console.log(a>30); //false
console.log(20> 20'); //false
>= Greater than or equal to It checks whether the value of the left operands is greater than or equal to the value of the right operand or not. let a = 20;
let b = 20;
console.log(a>=b); //true
console.log(a>=30); //false
console.log(20>='20'); //true
< Less than It checks whether the value of the left operands is less than the value of the right operand or not. let a = 10;
let b = 20;
console.log(a<b); //true
console.log(a<10); //false
console.log(10<'10'); //false
<= Less than or equal to It checks whether the value of the left operands is less than or equal to the value of the right operand or not. let a = 10; let b = 20;
console.log(a<=b); //true
console.log(a<=10); //true
Logical Operators
Operator Operator_ Description Example
Name
&& Logical It returns true if both the operands(expression) are let a = false;
AND true, otherwise returns false. let b = true;
console.log(a&&b); /false
console.log(b&&true); //true
console.log(b&&10); //10 which is also 'true'
console.log(a&&'10'); //false
|| Logical OR It returns true if any of the operands(expression) are let a = false;
true, otherwise returns false. let b = true;
console.log(a||b); //true
console.log(b||true); //true
console.log(b||10); //true
console.log(a||'10'); //'10' which is also 'true'
! Logical It returns the inverse result of an operand(expression). let a = 20;
NOT let b = 30;
console.log(!true); //false
console.log(!false); //true
console.log(!a); //false
console.log(!b); /false
console.log(!null); //true
Bitwise Operators
Operator Operator_Name Description Example
& Bitwise AND It returns the result of a Boolean AND operation on each bit of its integer arguments. let a = 2;
let b = 3;
let c = a & b;
console.log(c); // Output 2
| Bitwise OR It returns the result of a Boolean OR operation on each bit of its integer arguments. let a = 2;
let b = 3;
let c = a | b;
console.log(c); // Output 3
^ Bitwise XOR It returns the result of a Boolean Exclusive OR operation on each bit of its integer arguments. let a = 2;
let b = 3;
let c = a ^ b;
console.log(c); // Output 1
~ Bitwise NOT It inverts each bit in the operands. let a = 2;
let c = ~ a;
console.log(c); // Output -3
>> Bitwise Right The left operand's value is moved to the right by the number of bits specified in the right let a = 2;
Shift operand. let b = 3;
let c = a >> b;
console.log(c); // Output 0
<< Bitwise Left Shift The left operand's value is moved to the left by the number of bits specified in the right let a = 2;
operand. New bits are filled with zeroes on the right side. let b = 3;
let c = a << b;
console.log(c); // Output 16
>>> Bitwise Right The left operand's value is moved to the right by the number of bits specified in the right let a = 3;
Shift with Zero operand and zeroes are added on the left side. let b = 4;
let c = a >>> b;
console.log(c); // Output 0
Assignment Operators
Operator Operator_ Description Example
Name
= Assign It assigns values from right side to left side operand. let a = 10;
let b = 5;
console.log("a=b:" +a); //
Output 10
+= Add and It adds the left operand with the right operand and assigns the let a = 10;
assign result to the left side operand. let b = 5;
let c = a += b;
console.log(c); // Output 15
-= Subtract It subtracts the right operand from the left operand and let a = 10;
and assign assigns the result to the left side operand. let b = 5;
let c = a -= b;
console.log(c); // Output 5
*= Multiply It multiplies the left operand with the right operand and let a = 10;
and assign assigns the result to the left side operand. let b = 5;
let c = a *= b;
console.log(c); // Output 50
/= Divide and It divides the left operand with the right operand and assigns let a = 10;
assign the result to the left side operand. let b = 5;
let c = a /= b;
console.log(c); // Output 2
%= Modulus It divides the left operand with the right operand and assigns let a = 16;
and assign the result to the left side operand. let b = 5;
let c = a %= b;
console.log(c); // Output 1
Ternary Operator
expression ? expression-1 : expression-2;
Example:
let num = 10;
let result = (num > 0) ? "True":"False"
console.log(result);
//Output: True
Concatenation Operator
• Example:
let message = "Welcome to " + "WebX.0";
console.log("Result of String Operator: " +message);
• Output:
Result of String Operator: Welcome to WebX.0
Advanced Type Operators
Operator_Name Description Example
in It is used to check for the let Bike = {make: 'Honda', model: 'CLIQ', year:
existence of a property on 2018};
an object. console.log('make' in Bike); // Output: true
typeof It returns the data type of let message = "Welcome to " + "Techneo";
the operand. console.log(typeof message);
// Output: String
instanceof It is used to check if the let arr = [1, 2, 3];
object is of a specified console.log( arr instanceof Array ); // true
type or not. console.log( arr instanceof String ); // false
Decision Making in TypeScript
if statement if...else statement switch statement
Loops in TypeScript
Definite Loop: for loop Indefinite Loop: while loop do…while loop
break Statement
var i:number = 1
while(i<=10) {
if (i % 5 == 0) {
console.log ("The first multiple of 5 between 1 and 10
is : "+i)
break //exit the loop if the first multiple is found
}
i++
} //outputs 5 and exits the loop
continue Statement
var num:number = 0
var count:number = 0;
for(num=0;num<=20;num++) {
if (num % 2==0) {
continue
}
count++
}
console.log (" The count of odd values between 0 and 20 is: "+count)
// Function implementation
function getAverage(a: string | number, b: string | number, c: string | number): string {
var total = parseInt(a as string, 10) + parseInt(b as string, 10) + parseInt(c as string, 10);
var average = total / 3;
return 'The average is ' + average;
}
var result = getAverage(4, 3, 8); // Result: 'The average is 5'
console.log(result);
Arrow Function (Lambda Function)
Use of the above targets depend on the application and module loader you are using.