0% found this document useful (0 votes)
3 views

TypeScript Mod 2

The document provides a comprehensive overview of TypeScript, including its internal architecture, environment setup, types, variables, operators, functions, classes, and modules. It highlights TypeScript's advantages such as static type-checking and object-oriented features, as well as its similarities to JavaScript. Additionally, it includes examples, syntax rules, and multiple-choice questions for self-assessment.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

TypeScript Mod 2

The document provides a comprehensive overview of TypeScript, including its internal architecture, environment setup, types, variables, operators, functions, classes, and modules. It highlights TypeScript's advantages such as static type-checking and object-oriented features, as well as its similarities to JavaScript. Additionally, it includes examples, syntax rules, and multiple-choice questions for self-assessment.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

TypeScript

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.

The TypeScript Compiler:

app.ts tsc app.ts app.js


Compiler Configuration

tsconfig.json

cmd: tsc --init


Declaration file
•Extension .d.ts.
•works as an interface.
•declare keyword prefixed
•IntelliSense for JavaScript libraries like
jQuery.
TypeScript Language Services
-Editors and other tools to give better assistance features
e.g. automated refactoring and IntelliSense
-Exposes an additional layer around the core-compiler pipeline.
-standard typical editor operations
e.g. code formatting and outlining, colorization, statement
completion, signature help, etc.
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 Environment Setup

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

test.ts console.log(“Hello World”);


Compile tsc test.ts
test.js
console.log(“Hello World”);
Run node test.js
Output
Hello World
TypeScript Types, Variables, Operators

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

let isboolean:boolean = true


TypeScript Types

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

let first: number = 3.1; // number


let second: number = 0x12F; // hexadecimal
let third: number = 0o78 ; // octal
let fourth: number = 0b11001; // binary
Built-in Types
String
Represents the text
single or double quotation marks
expressions - $ {expr}
Built-in Types
Boolean
True or False

e.g. let result = true


Built-in Types
Void
var a :void = undefined
Function return type
function display():void{
console.log("Hi")
}
display()
Built-in Types
Null
Value is null
let num: number = null;
let bool: boolean = null;
let str: string = null;
console.log(num)

PS D:\Jan-June23\typescript> tsc test.ts


PS D:\Jan-June23\typescript> node test.js
null
Built-in Types
undefined
Value is undefined
let num: number = undefined;
console.log(num)

PS D:\Jan-June23\typescript> tsc test.ts


PS D:\Jan-June23\typescript> node test.js
undefined
Built-in Types
Any
super type
skip the type-checking on compile time.
let value: any;
value = "string"
value = 122
console.log(value)

PS D:\Jan-June23\typescript> tsc test.ts


PS D:\Jan-June23\typescript> node test.js
122
TypeScript Types

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 list : Array<number> = [1, 3, 5];


User-Defined
Tuple
Two sets of values of different data types.
// Declare a tuple
let b:[string, number, string, number]
// Initialize it
b = ["hi", 8, "hello", 9]; // OK
console.log(b)

PS D:\Jan-June23\typescript> tsc test.ts


PS D:\Jan-June23\typescript> node test.js
[ 'hi', 8, 'hello', 9 ]
User-Defined
Class
class Student
{
RollNo: number;
Name: string;
constructor(_rollNo: number, _name: string)
{
this.RollNo = _rollNo;
this.Name = _name;
}
showDetails()
{
console.log(this.RollNo + " : " + this.Name);
} }
User-Defined
Function
•Named function or as an anonymous function
•Named function with number as parameters type an
d return type.
•Anonymous function with number as parameters
type and return type
User-Defined
Function
•Named function or as an anonymous function
•Named function with number as parameters type an
d return type.
function add( a: number, b: numbe r number
): {
return a + b;
}
User-Defined
Function
•Named function or as an anonymous function
•Anonymous function with number as parameters
type and return type
let sum = function (a: number, y: number): number
{
return a + b;
};
User-Defined
Interface
defines the syntax that any entity must adhere to.
define properties, methods, and events.
contain only the declaration of the members.
It is the responsibility of the deriving class to define
the members.
User-Defined
Syntax
interface interface_name
{ }
Example
interface IPerson {
firstName:string,
lastName:string,
sayHi:()=>string
}
Example
interface IPerson {
firstName:string,
lastName:string, Blueprint
sayHi:()=>string
}

var customer:IPerson = {
firstName:"Tom",
Object
lastName:"Hanks",
sayHi:():string =>
{return "Hi there"} }
Example

console.log("Customer Object ")


console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())
User-Defined
Interface - Example
interface Calc {
subtract (first: number, second: number): any;
}

let Calculator: Calc = {


subtract(first: number, second: number) {
return first - second;
}
}
User-Defined

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“ }

function respond(recipient: string, message:


UserResponse): void {
// ...
console.log(recipient+":"+message)
}
respond("Princess Harsakshi", UserResponse.Yes );
Difference between constant and Enum
MCQs
Visit=>slido.com
Code=> 3276389
MCQs
How do you specify that a function does not return
anything in TypeScript?
A. function myFunc(): undefined
B. function myFunc(): void
C. function myFunc(): null
D. function myFunc(): None

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.

•Variable declaration=> let, const, var


Variable declaration=>
var [identifier] : [type-annotation] = value;
var [identifier] : [type-annotation];
var [identifier] = value;
var [identifier];
var keyword
Scoping rule: Variables declared in TypeScript
with the var keyword have function scope.
function a() {
var x = 50;
return function b() { 55
var y = x+5;
return y;
}
}
var c = a();
console.log(c());
let keyword
The Variable declared with the let keyword are scoped
to the nearest enclosing block which can be smaller than
a function block.
function a() {
var x = 50;
return function b() Error
{
let y = x+5;
}
return y;
}
var c = a();
console.log(c());
Re-declaration and Shadowing

Re-declaration: With the var declaration, it does


not matter how many time's we declared
variables. But there is some bug, which can be
found by the let declaration.
Re-declaration and Shadowing
Shadowing : declares an identifier which has already been
declared in an outer scope.
var nm:string = "Rehan";
function showMsg(message:string)
{
var nm = "Aashna"; Hi Aashna
console.log(message+nm);
}
showMsg("Hi ");
Hoisting
Hoisting of var
Hoisting is a mechanism of JavaScript. In
hoisting, variables and function declarations are
moved to the top of their enclosing scope before
code execution.

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;

1) var result= "5>3“ ? (first > second) : "5<3";

Correct code=>

var result= (first > second)? "5>3" : "5<3";


Ternary/Conditional Operator(?:)
Example:
let num = 17;
let result = (num %2==0 0) ? "True":"False"

console.log(result);

False
Type
Operators
• in, delete, typeof, instanceof

in=> It is used to check for the existence of a property


on an object.
e.g. let Bike = {make: 'Honda', model: 'CLIQ’}
console.log('make' in Bike);
// Output: true
Type
Operators
delete => It is used to delete the properties from the objects.

let Bike = { Company1: 'Honda', Company2: 'Hero’};


delete Bike.Company1;
console.log(Bike);
// Output: { Company2: 'Hero’}
Type
Operators
typeof=> It returns the data type of the operand.

let message="Welcome to " + "JavaTpoint";


console.log(typeof message);
// Output: String
Type
Operators
instanceof=>It is used to check if the object is of a
specified type or not.
let arr = [1, 2, 3];
console.log( arr instanceof Array );
// true
console.log( arr instanceof String );
// false
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
Decision Making statements

There are various types of Decision


making in TypeScript:
•if statement
•if-else statement
•if-else-if ladder
•nested if statement
if statement
if(condition) {
// code to be executed
}
if-else statement
if(condition) {
// code to be executed
} else {
// code to be executed
}
If-else-if ladder
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
Nested If-else ladder
if(condition1) {
//Nested if else inside the body of "if"
if(condition2) {
//Code inside the body of nested "if"
}
else {
//Code inside the body of nested "else"
}
}
else {
//Code inside the body of "else."
}
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
loops
TypeScript while loop

while (condition)
{
//code to be executed
}
TypeScript do-while loop

do{
//code to be executed
}while (condition);
TypeScript for loop

for (Ist exprn; IInd exprn; IIIrd exprn ) {


// statements to be executed repeatedly
} }
TypeScript for…of loop
Iterate and access the elements of an array,
string, set, map, list, or tuple collection.
for (var val of list) {
//statements to be executed
}
let arr = [1, 2, 3, 4, 5];
for (var val of arr) {
console.log(val);
}
TypeScript for..in loop
Iterates through a list or collection and returns an index
on each iteration. In this, the data type of "val" should be
a string or any. for (var val in list) {
//statements
}
let str:any = "JavaTpoint";
for (let index in str) {
console.log(`Index of ${str[index]}: ${index}`);

}
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.

(parameter1, parameter2, ..., parameterN) => expression;

• Arrow function with parameter


• Arrow function without a parameter
• Arrow function in a class
Arrow function in a class
class Student {
roll: number;
Name: string;
constructor(code: number, name: string) {
this.Name = name;
this.roll = code;
}
display = () => console.log("Student roll: "
+ this.roll + '\nStudent Name: ' + this.Name)
}
let s = new Student(21, 'Tom');
s.display();
Function Parameter
• Optional Parameter
• Default Parameter
• Rest Parameter
Optional Parameter

• Parameter is optional=> value is undefined


• question mark sign ('?’)
• parameters which may or may not receive a
value can be appended with a “?”
• Syntax:
function function_name(parameter1[:type], parameter2 ?[:type])
{}
Optional Parameter-Example
function display(id:number,n:string,roll?:number)
{
console.log("ID:", id, " Name:",n);
if(roll!=undefined)
console.log("roll:",roll);
}
display(101,"Minoli");
display(105,"Minoli",34);
Default Parameter
• Default values stored in function parameters.
• User does not pass a value to an argument.
• Same as an optional parameter.
• Cannot make the parameter optional and default at the
same time.

function function_name(p1[:type], p2[:type] = default_value)


{}
Default Parameter-Example
function display(name: string, msg: string =
"Welcome ")
: string {
return msg + name + '!';
}
console.log(display('Soham'));
console.log(display('Soham', 'Hello '));
console.log(display('Sachin'));

PS D:\Jan-June23\typescript> tsc parameters.ts


PS D:\Jan-June23\typescript> node parameters.js
Welcome Soham!
Hello Soham!
Welcome Sachin!
Rest Parameter
• Pass zero or more values to a function.
• Prefix the three "dot" characters ('...') before
the parameter
• different number of arguments
• Array of arguments
• Syntax:
function function_name(p1[:type], p2[:type], ...p3[:type])
{}
Rest Parameter
Rules:
• Only one rest parameter is allowed in a
function.
• It must be an array type.
• It must be the last parameter in a parameter
list.
Rest Parameter-Example
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);

PS D:\Jan-June23\typescript> tsc parameters.ts


PS D:\Jan-June23\typescript> node parameters.js
result2= 13
Function Overloading
• Create multiple methods with the same name but
different parameter types and return type.

The Function overloading is allowed when:


•The function name is the same
•The number of parameters is different in each overloaded
function.
•The number of parameters is the same, and their type is
different.
•The all overloads function must have the same return
type.
Function Overloading-Example
//Function with string type parameter
function add(a:string, b:string): string;
//Function with number type parameter
function add(a:number, b:number): number;
//Function Definition
function add(a: any, b:any): any {
return a + b;
}
console.log(add("Hi ","everyone"))
console.log(add(23, 12))
Function overloading in a class
class TEIT{
public display(v1:string);
public display(v2:number);
public display(v3:any):any{
if(typeof(v3)=="number")
{
return typeof(v3)
}
if(typeof(v3)=="string")
{
return v3
}
}
}
Function overloading in a class
var o = new TEIT()
console.log(o.display("er"))
console.log(o.display(23))

PS D:\Jan-June23\typescript> tsc parameters.ts


PS D:\Jan-June23\typescript> node parameters.js
er
number
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 Classes and Objects

• Creating Object of a class


• Data Hiding – Access
Modifiers(public, private, protected,
readonly)
• Inheritance – Single, Multilevel
• Interfaces
Creating Object of a class

Class Definition
class <class_name>{
field;
method;
}

Creating object of a class=>


var objectnm= new Classnm(parameters)
Data Hiding
• To hide the internal object details.
• Controls the visibility of its data members from
the members of the other classes.
• Encapsulation
• Access modifier - Visibility of class data member
Data Hiding
• To hide the internal object details.
• Controls the visibility of its data members from
the members of the other classes.
• Encapsulation
• Access modifier - Visibility of class data member
Data Hiding
Public
by default, all the members (properties and methods) of a class are
public.
access this data member anywhere without any restriction.
class Student {
public studCode: number;
studName: string;
}

let stud = new Student();


stud.studCode = 101;
stud.studName = "Joe Root";
Data Hiding
Private
The private access modifier cannot be accessible outside of its
containing class. It ensures that the class members are visible
only to that class in which it is containing.
class Student {
public studCode: number;
private studName: string;
}

let stud = new Student();


stud.studCode = 101;
stud.studName = "Joe Root";
Data Hiding
Private
The private access modifier cannot be accessible outside of its
containing class. It ensures that the class members are visible
only to that class in which it is containing.
class Student {
public studCode: number;
private studName: string;
}

let stud = new Student();


stud.studCode = 101;
stud.studName = "Joe Root"; Error
Data Hiding
A Protected access modifier can be accessed only within the class
and its subclass. We cannot access it from the outside of a class
in which it is containing.
Data Hiding
Readonly Modifier

•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”;
}

let stud = new Student();


stud.studCode = 101; Error
stud.studName = "Joe Root";
Data Hiding
Readonly Modifier
class Student {
public studCode: number;
readonly studName: string=
“xyz”;
}

let stud = new Student();


stud.studCode = 101; Error
stud.studName = "Joe Root";
class test{
name:string
public age:number
constructor(n:string, a:number){
this.name = n;
this.age = a;
}
display(){
console.log(this.name, this.age)
}
}

var o1 = new test("wer", 45);


O1.display();
o1.age=23
o1.display()
class test{
name:string
private age:number
constructor(n:string, a:number){
this.name = n;
this.age = a;
}
display(){
console.log(this.name, this.age)
}
}

var o1 = new test("wer", 45);


O1.display();
o1.age=23
o1.display()
Error
class test{
name:string
readonly age:number
constructor(n:string, a:number){
this.name = n;
this.age = a;
}
display(){
console.log(this.name, this.age)
} }
var o1 = new test("wer", 45);
O1.display();
o1.age=23
o1.display()
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()
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

Ternary operator example


let num = 17;
let result = (num %2==0 0) ? "True":"False"
console.log(result);

Output=> False

Type operators with example


• in, delete, typeof, instanceof
=>in
e.g. let Bike = {make: 'Honda', model: 'CLIQ’}
console.log('make' in Bike);
// Output: true

=>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();

//output=> Hello JavaTpoint!

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

Function Overloading in TypeScript


//Function with string type parameter
function add(a:string, b:string): string;
//Function with number type parameter
function add(a:number, b:number): number;
//Function Definition
function add(a: any, b:any): any {
return a + b;
}
console.log(add("Hi ","everyone"))
console.log(add(23, 12))
//Output
Hi everyone
35
Function overloading in a class
class TEIT{
public display(v1:string);
public display(v2:number);
public display(v3:any):any{
if(typeof(v3)=="number")
{
return typeof(v3)
}
if(typeof(v3)=="string")
{
return v3
}
}
}
var o = new TEIT()
console.log(o.display("er"))
console.log(o.display(23))

//Output
PS D:\Jan-June23\typescript> tsc parameters.ts
PS D:\Jan-June23\typescript> node parameters.js
er
number

Function parameters(Optional, Default, Rest) in


TypeScript.
Optional Parameter=>
function display(id:number,n:string,roll?:number) {
console.log("ID:", id, " Name:",n);
if(roll!=undefined)
console.log("roll:",roll);
}
display(101,"Minoli");
display(105,"Minoli",34);
//Output=>
Default Parameter
function display(name: string, msg: string = "Welcome ")
: string {
return msg + name + '!';
}
console.log(display('Soham'));
console.log(display('Soham', 'Hello '));
console.log(display('Sachin'));
//Output
PS D:\Jan-June23\typescript> tsc parameters.ts
PS D:\Jan-June23\typescript> node parameters.js
Welcome Soham!
Hello Soham!
Welcome Sachin!

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

single inheritance in TypeScript


Example=>
class student{
//field
name:string
id:number
constructor(n:string, id:number)
{
this.name = n;
this.id = id;
}
display():void{
console.log(this.name, this.id)
}
}
class stu1 extends student{
roll:number
constructor(n:string, id:number, roll:number)
{
super(n, id)
this.roll = roll
}
display1():void{
console.log(this.roll)
}
}

let o2 = new stu1("Sania", 12, 1)


o2.display()
o2.display1()

//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

You might also like