TypeScript Mod 2
TypeScript Mod 2
Module2
Points
• Overview
• TypeScript Internal Architecture
• TypeScript Environment Setup
• TypeScript Types, variables and
operators
• Decision Making and loops
• TypeScript Functions
• TypeScript Classes and Objects
• TypeScript Modules
Points
• Overview
• TypeScript Internal Architecture
• TypeScript Environment Setup
• TypeScript Types, variables and operators
• Decision Making and loops
• TypeScript Functions
• TypeScript Classes and Objects
• TypeScript Modules
What is TypeScript??
• Open source, Object-oriented
• Maintained by Microsoft and licensed under
Apache 2.
• Extends JavaScript – Type-checking, object
oriented features
• Superset
• ES6 version
Why TypeScript??
• JavaScript doesn’t check assigned values.
• Type System – Code quality, readability, easy
to maintain, errors.
• Object oriented features.
• TypeScript compiles into JavaScript.
How to use??
• Install typescript
TSC
file.ts Compile Execute file.js
File.ts
TypeScript Features
• Cross-Platform
• Object-Oriented Language
• Static Type-checking
• Optional Static Typing
• DOM Manipulation
• ES6 Features
TypeScript Advantages
• Open-source
• Similar to JavaScript
• Closer in syntax to Java and Scala
• Works with JS frameworks
• Runs on any browser
Points
• Overview
• TypeScript Internal Architecture
• TypeScript Environment Setup
• TypeScript Types, variables and operators
• Decision Making and loops
• TypeScript Functions
• TypeScript Classes and Objects
• TypeScript Modules
TypeScript Internal Architecture
Language: syntax, keywords, and type annotations.
tsconfig.json
1) Install Node.js
2) Install TypeScript
npm install typescript -g
//Install as a global module
npm install typescript@latest -g
//Install latest if you have an older version
3)To check successful installation=> tsc -v
Points
• Overview
• TypeScript Internal Architecture
• TypeScript Environment Setup
• TypeScript Types, variables and operators
• Decision Making and loops
• TypeScript Functions
• TypeScript Classes and Objects
• TypeScript Modules
First Program
TypeScript Types
TypeScript Data Types Syntax
[Keyword] [Variable Name]:[Data Type] = [Value];
[Keyword] [Variable Name]:[Data Type] ;
let, number,
const, string,
var boolean
e.g. let name:string = “Shriya”
let age:number = 38
Built-in Use-Defined
Number Array
Void Tuple
String Enum
Boolean Function
Null Class
Interface
TypeScript Types
Built-in Use-Defined
Number Array
Void Tuple
String Enum
Boolean Function
Null Class
Interface
Built-in Types
Number
Integers, fractions, Binary, Octal, Decimal,
Hexadecimal
Built-in Use-Defined
Number Array
Void Tuple
String Enum
Boolean Function
Null Class
Interface
TypeScript Types
Built-in User-Defined
Number Array
Void Tuple
String Enum
Boolean Function
Null Class
Interface
MCQs
Which of the following will transpile a
TypeScript file (example.ts) to JavaScript?
A. typescript example.ts
B. ts-compile example.ts
C. tsc example.ts
D. ts example.ts
Answer:
C. tsc example.ts
How do you declare a variable that can be a string
in TypeScript?
A. let variable: string ;
B. let variable: str;
C. let variable: String;
D. All of the above;
Answer:
A. let variable: string ;
Which command would you use to install TypeScript globally
using npm?
A. npm install typescript
B. npm global install typescript
C. npm install -g typescript
D. npm typescript install global
Answer:
C. npm install -g typescript
What is the inherited type for the variable example
in 'const example = [‘Varad’]'?
A) any[]
B) string[]
C) string
D) unknown[]
Answer :
Option (B) : string[]
Self Learning:
Difference between null and undefined
User-Defined
Array
Collection of values
Two ways:
var list : number[] = [1, 3, 5];
var customer:IPerson = {
firstName:"Tom",
Object
lastName:"Hanks",
sayHi:():string =>
{return "Hi there"} }
Example
Enums
• Allow a developer to define a set of named constants.
• String-based and numeric-based
• Enum can be defined using enum keyword
• Numbering starts from 0
Enums
Number enums
2
3
4
0
1
2
3
Enums
String enums
Heterogenous
enums
User-Defined
Enums
•Set of named constant
•String-based and numeric-based
•Numbering starts from 0
enum UserResponse {
No=0,
Yes = "smart“ }
ans=>B
How do you define an array of strings in TypeScript?
A. Array<string>
B. string[]
C. Both A and B
D. List<string>
Answer:
C. Both A and B
How do you declare a class in TypeScript?
A. def ClassName:
B. class ClassName {}
C. new Class ClassName {}
D. object ClassName {}
Answer:
B. class ClassName {}
28. How do you create an instance of a TypeScript class?
A. new MyClass()
B. MyClass.new()
C. MyClass.create()
D. instance MyClass()
Answer:
A. new MyClass()
Points
• Overview
• TypeScript Internal Architecture
• TypeScript Environment Setup
• TypeScript Types, variables and operators
• Decision Making and loops
• TypeScript Functions
• TypeScript Classes and Objects
• TypeScript Modules
Variables
A variable is the storage location, which is used to store
value/information to be referenced and used by programs.
Rules=>
• alphabet or numeric digits.
• The variable name cannot start with digits.
• The variable name cannot contain spaces and special
character, except the underscore(_) and
the dollar($) sign.
Hoisting of let
A variable declared with let keyword is not
hoisted. If we try to use a let variable before it is
declared, then it will result in a ReferenceError.
const declarations
The const declaration is used to declare
permanent value, which cannot be changed later.
It has a fixed value. The const declaration
follows the same scoping rules as let
declaration, but we cannot re-assign any new
value to it.
Points
• Overview
• TypeScript Internal Architecture
• TypeScript Environment Setup
• TypeScript Types, variables and operators
• Decision Making and loops
• TypeScript Functions
• TypeScript Classes and Objects
• TypeScript Modules
operators
•Arithmetic operators
•Comparison (Relational) operators
•Logical operators
•Bitwise operators
•Assignment operators
•Ternary/conditional operator
•Concatenation operator
•Type Operator
operators
•Arithmetic operators
•Comparison (Relational) operators
•Logical operators
•Bitwise operators
•Assignment operators
•Ternary/conditional operator
•Concatenation operator
•Type Operator
operators
•Arithmetic operators
•Comparison (Relational) operators
•Logical operators
•Bitwise operators
•Assignment operators
•Ternary/conditional operator
•Concatenation operator
•Type Operator
Ternary/Conditional Operator(?:)
Syntax:
expression ? expression-1 : expression-2;
expression: It refers to the conditional expression.
expression-1: If the condition is true,
expression-1 will be returned.
expression-2: If the condition is false,
expression-2 will be returned.
Example
Check and correct
var first = 5;
var second = 3;
Correct code=>
console.log(result);
False
Type
Operators
• in, delete, typeof, instanceof
while (condition)
{
//code to be executed
}
TypeScript do-while loop
do{
//code to be executed
}while (condition);
TypeScript for loop
}
Points
• Overview
• TypeScript Internal Architecture
• TypeScript Environment Setup
• TypeScript Types, variables and operators
• Decision Making and loops
• TypeScript Functions
• TypeScript Classes and Objects
• TypeScript Modules
TypeScript Functions
Named function
Anonymous function
Arrow Function
Function Parameter
Function Overloading
TypeScript Functions
Named function
//Function Definition
function display() {
console.log("Hello JavaTpoint!");
}
//Function Call
display();
TypeScript Functions
Anonymous function - A function without a
name
// Anonymous function
let myAdd = function (x: number, y: number) : number
{
return x + y;
};
// Anonymous function call
console.log(myAdd(5,3));
Arrow Function
Elements:
•Parameters: A function may or may not have parameters.
•The arrow notation/lambda notation (=>)
•Statements: It represents the function's instruction set.
Class Definition
class <class_name>{
field;
method;
}
•We can make the properties of the class, type, or interface readonly
by using the readonly modifier.
•This modifier needs to be initialized at their declaration time or in
the constructor.
•We can also access readonly member from the outside of a class, but
its value cannot be changed.
Data Hiding
Readonly Modifier
class Student {
public studCode: number;
readonly studName: string=
“xyz”;
}
}
var o = new test1("wer", 45, "Mumbai");
o.display()
o.display1()
o1.age=23
Error
Inheritance
• Single
• Multilevel
Inheritance
• Single
• Multilevel
Use of super method to implement single
inheritance
class test{
name:string
protected age:number
constructor(n:string, a:number){
this.name = n;
this.age = a;
}
display(){
console.log(this.name, this.age)
}
}
class test1 extends test{
city:string
constructor(n:string, a:number, c:string){
super(n, a);
this.city = c;
}
display1(){
console.log(this.city)
}
}
var o = new test1("wer", 45, "Mumbai");
o.display()
o.display1()
PS D:\Priya\2023-24\Web X.0\Jan-June23\Typescript> tsc expt4.ts
PS D:\Priya\2023-24\Web X.0\Jan-June23\Typescript> node
expt4.js
wer 45
Module 2 - codes
“any” data type example
let value: any;
value = "string"
value = 122
console.log(value)
Output=>
PS D:\Jan-June23\typescript> tsc test.ts
PS D:\Jan-June23\typescript> node test.js
122
Array
⮚ Two ways:
⮚ var list : number[] = [1, 3, 5];
⮚ var list : Array<number> = [1, 3, 5];
e. g.
var list:number[] = [1, 3, 5]
console.log(list[0])
Output=>1
Tuple example
// Declare a tuple
let b:[string, number, string, number]
// Initialize it
b = ["hi", 8, "hello", 9]; // OK
console.log(b)
Output=>
PS D:\Jan-June23\typescript> tsc test.ts
PS D:\Jan-June23\typescript> node test.js
[ 'hi', 8, 'hello', 9 ]
Enum example
enum UserResponse {
No=0,
Yes = "smart"
}
function respond(recipient: string, message:
UserResponse): void {
// ...
console.log(recipient+":"+message)
}
Function call=>
respond("Princess", UserResponse.Yes);
Output=>
Princess:smart
interface example
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
console.log(customer)
console.log("Customer Object ")
console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())
Output=>
D:\Jan-June23\Typescript> tsc test.ts
PS D:\Jan-June23\Typescript> node test.js
{ firstName: 'Tom', lastName: 'Hanks', sayHi: [Function:
sayHi] }
Customer Object
Tom
Hanks
Hi there
Output=> False
=>delete
let Bike = { Company1: 'Honda', Company2: 'Hero’};
delete Bike.Company1;
console.log(Bike);
// Output: { Company2: 'Hero’}
=>typeof
let message="Welcome to " + "JavaTpoint";
console.log(typeof message);
// Output: String
=>instanceof
let arr = [1, 2, 3];
console.log( arr instanceof Array );
// true
console.log( arr instanceof String );
// false
Named Function
//Function Definition
function display() {
console.log("Hello JavaTpoint!");
}
//Function Call
display();
Anonymous function
// Anonymous function
let myAdd = function (x: number, y: number) : number {
return x + y;
};
// Anonymous function call
console.log(myAdd(5,3));
//output
8
//Output
PS D:\Jan-June23\typescript> tsc parameters.ts
PS D:\Jan-June23\typescript> node parameters.js
er
number
Rest parameter
function add(a: number, ...b: number[]): number {
let r = a;
for (var i = 0; i < b.length; i++) {
r += b[i];
}
return r;
}
let result1 = add(4, 5);
let result2 = add(4, 2, 2, 5);
//Output
PS D:\Jan-June23\typescript> tsc parameters.ts
PS D:\Jan-June23\typescript> node parameters.js
result2= 13
//Output
Sania 12
1
Module 2
• Definition, TypeScript features, advantages, disadvantages=>
https://www.javatpoint.com/typescript-features
• TypeScript Internal Architecture
https://www.javatpoint.com/typescript-components
• TypeScript Environment Setup
https://www.javatpoint.com/typescript-installation
• TypeScript Types, variables and operators
https://www.javatpoint.com/typescript-types
https://www.tutorialspoint.com/typescript/typescript_interface
s.htm
https://www.typescriptlang.org/docs/handbook/enums.html
https://www.javatpoint.com/typescript-operators
https://www.javatpoint.com/typescript-variables
• Decision Making and loops
https://www.javatpoint.com/typescript-indefinite-loops
https://www.javatpoint.com/typescript-definite-loop
https://www.javatpoint.com/typescript-decision-making
• TypeScript Functions, Types of parameters
https://www.javatpoint.com/typescript-function
https://www.tutorialsteacher.com/typescript/function-overload
ing
https://www.geeksforgeeks.org/how-to-achieve-function-overl
oading-in-typescript/
• TypeScript Classes and Objects
https://www.javatpoint.com/typescript-classes
https://www.javatpoint.com/typescript-inheritance