TYPESCRIPT
SUNITA D. RATHOD
WHAT IS TYPESCRIPT?
• TypeScript is an open-source, object-oriented
language developed and maintained by Microsoft,
licensed under Apache 2 license.
• It was introduced by Anders Hejlsberg, a core
member of the development team of C# language.
• TypeScript extends JavaScript by adding data types,
classes, and other object-oriented features with
type-checking. It is a typed superset of JavaScript
that compiles to plain JavaScript.
WHAT IS TYPESCRIPT?
• TypeScript is the ES6
version of JavaScript with
some additional features.
• TypeScript uses TSC (TypeScript Compiler) compiler,
which convert Typescript code (.ts file) to JavaScript
(.js file).
Typescript Features
• Cross-Platform
• Object-Oriented Language
• Static type-checking
• Optional Static Typing
• DOM Manipulation
• ES 6 Features
TypeScript vs. JavaScript
TypeScript JavaScript
TypeScript is a heavy weight and
strongly typed object oriented
compile language which is
developed by Microsoft.
JavaScript on other hand is a light
weight interpreted language and is
introduced by Netscape.
Internal implementation of
TypeScript does not allow it to be
used at server side. It can only be
used at client side.
JavaScript can be used both at
client side and server side.
For binding the data at code level
TypeScript uses concepts like types
and interfaces to describe data
being used.
No such concepts has been
introduced in JavaScript.
Typescript vs. JavaScript
TypeScript JavaScript
Code written in TypeScript first
need to get compiled and then
converted to JavaScript this
process of conversion is known as
Trans-piled.
No compilation is needed in case
of JavaScript.
TypeScript gives support for
modules hence allows the modular
programming.
JavaScript does not support
modules and hence do not allow
the modular programming.
Any number of optional
parameters are allowed in function
code written in TypeScript.
JavaScript does not support
optional parameter function.
First Program
var message = "HelloWorld";
console.log(message);
Output:
HelloWorld
//FileName: filename.ts
TypeScript Types
[Keyword] [Variable Name]: [Data Type] = [Value];
OR
[Keyword] [Variable Name]: [Data Type];
• [Keyword]: var, let or const to define the scope and usage of
variable.
• [Data Type]: number, string, boolean, etc.
var uname : string = “Sunita Rathod"; // string
var age : number= 44; // number
var isUpdated : boolean = true; // boolean
Type Annotations
Example: Type Annotation of Parameters
function display(id:number, name:string)
{
console.log("Id = " + id + ", Name = " + name);
}
Example: Type Annotation in Object
var employee : {
id: number;
name: string; };
employee = { id: 100, name : "John" }
TypeScript - Variable
• TypeScript follows the same rules as JavaScript for variable
declarations.
• Variables can be declared using: var, let, and const.
Example: Variable Declaration using let
let employeeName = "John";
// or
let employeeName:string = "John";
Advantages of let over var
• Block-scoped let variables cannot be read or written to before
they are declared.
Example: let vs var
console.log(num1); // Compiler Error: error TS2448:
Block-scoped variable 'num' used
before its declaration
let num1:number = 10 ;
console.log(num2); // OK, Output: undefined
var num2:number = 10 ;
Advantages of let over var
• Let variables cannot be re-declared
Example: Multiple Variables with the Same Name
var num:number = 1; // OK
var Num:number = 2; // OK
var NUM:number = 3; // OK
var NuM:number = 4; // OK
let num:number = 5; // Compiler Error: Cannot redeclared block-scoped variable 'num'
let Num:number = 6; // Compiler Error: Cannot redeclared block-scoped variable 'Num'
let NUM:number = 7; // Compiler Error: Cannot redeclared block-scoped variable 'NUM'
let NuM:number = 8; // Compiler Error: Cannot redeclared block-scoped variable 'NuM'
var vs let
Const
• The const makes a variable a constant where its value cannot
be changed.
Example: Const Variable
const num:number = 100;
num = 200; //Compiler Error: Cannot assign to 'num'
because it is a constant or read-only property
const num:number; //Compiler Error: const declaration
must be initialized
num = 100;
TypeScript Data Type
Number
Example: TypeScript Number Type Variables
let first:number = 123; // number
let second: number = 0x37CF; // hexadecimal
let third:number=0o377 ; // octal
let fourth: number = 0b111001; // binary
console.log(first); // 123
console.log(second); // 14287
console.log(third); // 255
console.log(fourth); // 57
String
• String values are surrounded by single quotation marks or
double quotation marks.
Example: TypeScript String Type Variable
let employeeName:string = 'John Smith';
//OR
let employeeName:string = "John Smith";
Boolean
• Boolean values are supported by both JavaScript and
TypeScript and stored as true/false values.
Example: TypeScript String Type Variable
let isPresent:boolean = true;
Void
• void is used where there is no data.
• For example, if a function does not return any value then you
can specify void as return type.
Example: void
function sayHi(): void {
console.log('Hi!')
}
let speech: void = sayHi();
console.log(speech); //Output: undefined
Null vs. Undefined
SN Null Undefined
1. It is an assignment value. It can be
assigned to a variable which
indicates that a variable does not
point any object.
It is not an assignment value. It means a
variable has been declared but has not
yet been assigned a value.
2. It is an object. It is a type itself.
3. The null value is a primitive value
which represents the null, empty,
or non-existent reference.
The undefined value is a primitive
value, which is used when a variable
has not been assigned a value.
4. Null indicates the absence of a
value for a variable.
Undefined indicates the absence of the
variable itself.
5. Null is converted to zero (0) while
performing primitive operations.
Undefined is converted to NaN while
performing primitive operations.
Never
• TypeScript introduced a new type never, which indicates the
values that will never occur.
Example: never
function throwError(errorMsg: string): never {
throw new Error(errorMsg);
}
function keepProcessing(): never {
while (true) {
console.log('I always does something and never ends.')
}
}
Arrays
• An array is a special type of data type which can store multiple
values of different data types sequentially using a special
syntax.
• let fruits: string[] = ['Apple', 'Orange', 'Banana'];
• let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
• let arr = [1, 3, 'Apple', 'Orange', 'Banana', true, false];
Tuples
• Tuple can contain two values of different data types.
Example: Tuple vs Other Data Types
var empId: number = 1;
var empName: string = "Steve";
// Tuple type variable var
employee: [number, string] = [1, "Steve"];
Accessing Tuple Elements
• We can access tuple elements using index, the same way as an
array. An index starts from zero.
Example: Accessing Tuple
var employee: [number, string] = [1, "Steve"];
employee[0]; // returns 1
employee[1]; // returns "Steve"
Add Elements into Tuple
• You can add new elements to a tuple using the push() method.
Example: push()
var employee: [number, string] = [1, "Steve"];
employee.push(2, "Bill");
console.log(employee); //Output: [1, 'Steve', 2, 'Bill']
Enum
• enums allow us to declare a set of named constants i.e. a
collection of related values that can be numeric or string
values.
• There are three types of enums:
1. Numeric enum
2. String enum
3. Heterogeneous enum
Example: Numeric Enum
enum PrintMedia {
Newspaper,
Newsletter,
Magazine,
Book
}
Union
• TypeScript allows us to use more than one data type for a
variable or a function parameter.
• This is called union type.
Syntax:
(type1 | type2 | type3 | .. | typeN)
Example: Union
let code: (string | number);
code = 123; // OK
code = "ABC"; // OK
code = false; // Compiler Error
Any
• TypeScript has type-checking and compile-time checks.
However, we do not always have prior knowledge about the
type of some variables, especially when there are user-
entered values from third party libraries.
• In such cases, we need a provision that can deal with dynamic
content. The Any type comes in handy here.
Example: Any
let something: any = "Hello World!";
something = 23;
something = true;
Type Inference in TypeScript
• TypeScript infers types of variables when there is no explicit
information available in the form of type annotations.
• Types are inferred by TypeScript compiler when:
• Variables are initialized
• Default values are set for parameters
• Function return types are determined
For example,
var a = "some text";
var b = 123;
a = b; // Compiler Error: Type 'number' is not assignable to type 'string'
Operators in TypeScript
• In TypeScript, an operator can be classified into the following
ways.
• Arithmetic operators : (+, -, *, /, %, ++, --)
• Comparison (Relational) operators : (<, >, <=, >=, ==, !=)
• Logical operators : ( &&, ||, !)
• Bitwise operators : (&, |, ^, ~, >>, <<, >>>)
• Assignment operators : (=, +=, -=, *=, /=, %=)
• Ternary/conditional operator : ( condition ? True : false)
• Concatenation operator : ( + )
• Type Operator
Type Operators
Decision Making in TypeScript
if statement if…else statement
Decision Making in TypeScript
Switch Statement
Loops in TypeScript
• We can classify the loops into two types:
• Indefinite
• Definite
Indefinite Loop
While loop Do while loop
Definite Loop
For loop
break Statement
continue Statement
Have a nice day
Functions in TypeScript
• Functions are the fundamental building block of any
applications in JavaScript.
• It makes the code readable, maintainable, and reusable.
• We can use it to build up layers of abstraction, mimicking
classes, information hiding, and modules.
Function Aspects
Function declaration
function functionName( [arg1, arg2, ...argN] );
Function definition
function functionName( [arg1, arg2, ...argN] ){
//code to be executed
}
Function call
FunctionName();
Function creation
• We can create a function in two ways. These are:
1. Named Functions
2. Anonymous Function
Function creation
1. Named Function
Syntax: functionName( [arguments] ) { }
Example:
//Function Definition
function display() {
console.log("Hello WebX.0!");
}
//Function Call
display(); // Hello WebX.0!
Function creation
2. Anonymous Function
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)); // 5
Function Parameters
Example: Function Parameters
function Greet(greeting: string, name: string ) : string {
return greeting + ' ' + name + '!’;
}
Greet('Hello','Steve');//OK, returns "Hello Steve!"
Greet('Hi'); // Compiler Error: Expected 2 arguments, but got 1.
Greet('Hi','Bill','Gates'); //Compiler Error: Expected 2 arguments, but
got 3.
Optional Parameters
• Example: Optional Parameter
function Greet(greeting: string, name?: string )
: string {
return greeting + ' ' + name + '!’;
}
Greet('Hello','Steve');//OK, returns "Hello Steve!"
Greet('Hi'); // OK, returns "Hi undefined!".
Greet('Hi','Bill','Gates');//Compiler Error: Expected
2 arguments, but got 3.
TypeScript Arrow Function
• It omits the function keyword.
• We can call it fat arrow (=>)
• It is also called as Lambda function.
• The arrow function has lexical scoping of "this" keyword
Syntax:
(parameter1, parameter2, ..., parameterN) => expression;
TypeScript Arrow function
Arrow function with Parameter
let sum = (x: number, y: number): number => {
return x + y;
}
console.log(sum(10, 20));
Output :
30
TypeScript Arrow function
Arrow function without a parameter
let Print = () => console.log("Hello TypeScript");
Print();
Output:
Hello TypeScript
Function overloading
• TypeScript provides the concept of function overloading.
• You can have multiple functions with the same name but
different parameter types and return type. However, the
number of parameters should be the same.
• Function overloading is also known as method
overloading.
Function Overloading
• Advantages of function overloading
1. It saves the memory space so that program execution
becomes fast.
2. It provides code reusability, which saves time and
efforts.
3. It increases the readability of the program.
4. Code maintenance is easy.
Classes and Objects
• In object-oriented programming languages like Java and
C#, classes are the fundamental entities used to create
reusable components.
• TypeScript introduced classes to avail the benefit of
object-oriented techniques like encapsulation and
abstraction.
• The class in TypeScript is compiled to plain JavaScript
functions by the TypeScript compiler to work across
platforms and browsers.
Classes and Objects
• A class definition can contain the following properties:
1. Fields: It is a variable declared in a class.
2. Methods: It represents an action for the object.
3. Constructors: It is responsible for initializing the object
in memory.
4. Nested class and interface: It means a class can contain
another class.
Classes and Objects
Syntax to declare a class
A class keyword is used to declare a class in TypeScript. We can
create a class with the following syntax:
class <class_name>{
field;
method;
}
Object Creation
Syntax: let object_name = new class_name(parameter)
Object Initialization
• Object initialization means storing of data into the
object.
• There are three ways to initialize an object. These are:
1. By Reference Variable
2. By Method
3. By Constructor
Inheritance
• Inheritance is the ability of a program to create a new
class from an existing class.
• It is a mechanism which acquires the properties and
behaviors of a class from another class.
• The class whose members are inherited is called the base
class, and the class that inherits those members is called
the derived/ child/ subclass.
Inheritance
• In child class, we can override or modify the behaviors of its
parent class.
• The TypeScript uses class inheritance through the extends
keyword.
• TypeScript supports only single inheritance and multilevel
inheritance. It doesn't support multiple and hybrid
inheritance.
• We can use inheritance for Method Overriding (so runtime
polymorphism can be achieved) and code reusability.
Interfaces
• An Interface is a structure which acts as a contract in our
application.
• It defines the syntax for classes to follow.
• We cannot instantiate the interface, but it can be
referenced by the class object that implements it.
• The interface contains only the declaration of the
methods and fields, but not the implementation.
Interfaces
Syntax:
interface interface_name {
// variables' declaration
// methods' declaration
}
Modules
• A module is a way to create a group of related variables,
functions, classes, and interfaces, etc.
• It executes in the local scope, not in the global scope.
• We can create a module by using the export keyword
and can use in other modules by using
the import keyword.
• Modules import another module by using a module
loader.
Modules
• The most common modules loaders which are used in
JavaScript are the CommonJS module loader
for Node.js and require.js for Web applications.
• Steps:
1. Module Creation
2. Accessing the module in another file by using the
import keyword.
3. Compiling and Execution of Modules
Modules
Example: Let us understand the module with the following
example.
1. Module Creation
//FileName: addition.ts
export class Addition{
constructor(private x: number, private y: number){
}
Sum(){
console.log("SUM: " +(this.x + this.y));
}
}
Modules
2. Accessing the module in another file by using the
import keyword.
//FileName: app.ts
import {Addition} from './addition';
let addObject = new Addition(10, 20);
addObject.Sum();
Modules
3. Compiling and Execution of Modules
Open the terminal and go to the location where you stored
your project. Now, type the following command in the
terminal window.
$ tsc --module commonjs app.ts
$ node ./app.js
Output:
SUM: 30
Have a nice day

More Related Content

PPTX
typescript.pptx
PDF
TypeScript Interview Questions PDF By ScholarHat
DOC
Typescript Basics
PPTX
Complete Notes on Angular 2 and TypeScript
PPTX
Typescript-7 (1).pptx
PPTX
TypeScript Overview
PPT
TypeScript.ppt LPU Notes Lecture PPT for 2024
PPTX
Typescript
typescript.pptx
TypeScript Interview Questions PDF By ScholarHat
Typescript Basics
Complete Notes on Angular 2 and TypeScript
Typescript-7 (1).pptx
TypeScript Overview
TypeScript.ppt LPU Notes Lecture PPT for 2024
Typescript

Similar to TYPESCRIPT.pdfgshshhsjajajsjsjjsjajajjajjj (20)

PDF
Back to the Future with TypeScript
PPTX
PPTX
TypeScript: Basic Features and Compilation Guide
PDF
TypeScript introduction to scalable javascript application
PPTX
Type script - advanced usage and practices
PPT
Learning typescript
PPTX
002. Introducere in type script
PPTX
Introduction to TypeScript
PPTX
Typescript language extension of java script
PPTX
Typescript ppt
PDF
Introduction to TypeScript
PDF
TypeScript - An Introduction
PDF
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
PDF
Angular - Chapter 2 - TypeScript Programming
PDF
Introduction to TypeScript by Winston Levi
PPTX
Type script is awesome
ODP
Getting started with typescript and angular 2
PPTX
Typescript: Beginner to Advanced
PPTX
Getting started with typescript
PDF
Types For Frontend Developers
Back to the Future with TypeScript
TypeScript: Basic Features and Compilation Guide
TypeScript introduction to scalable javascript application
Type script - advanced usage and practices
Learning typescript
002. Introducere in type script
Introduction to TypeScript
Typescript language extension of java script
Typescript ppt
Introduction to TypeScript
TypeScript - An Introduction
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
Angular - Chapter 2 - TypeScript Programming
Introduction to TypeScript by Winston Levi
Type script is awesome
Getting started with typescript and angular 2
Typescript: Beginner to Advanced
Getting started with typescript
Types For Frontend Developers
Ad

Recently uploaded (20)

PPTX
28 - relative valuation lecture economicsnotes
PDF
NewBase 22 August 2025 Energy News issue - 1818 by Khaled Al Awadi_compresse...
PPTX
2. RBI.pptx202029291023i38039013i92292992
PDF
Modern Advanced Accounting in Canada, 9th Edition by Darrell Herauf, Murray H...
PDF
International Financial Management, 9th Edition, Cheol Eun, Bruce Resnick Tuu...
PPTX
Simple linear regression model an important topic in econometrics
PDF
Chapterrrrrrrrrrrrrrrrrrrrrrrrr 2_AP.pdf
PPTX
Machine Learning (ML) is a branch of Artificial Intelligence (AI)
PPTX
ANALYZE MARKET DEMAND, MARKET SUPPLY AND MARKET.pptx
PPT
Relevant Information & Alternative Choice Decisions
PPTX
Lesson Environment and Economic Growth.pptx
PPTX
PROFITS AND GAINS OF BUSINESS OR PROFESSION 2024.pptx
PDF
USS pension Report and Accounts 2025.pdf
PDF
Very useful ppt for your banking assignments BANKING.pptx.pdf
PPT
Project_finance_introduction in finance.ppt
PPTX
Group Presentation Development Econ and Envi..pptx
PPTX
The Impact of Remote Work on Employee Productivity
PDF
01 KEY PROVISIONS on NGPA and PROFESSIONALIZATION.pdf
PDF
Financial discipline for educational purpose
PDF
In July, the Business Activity Recovery Index Worsened Again - IER Survey
28 - relative valuation lecture economicsnotes
NewBase 22 August 2025 Energy News issue - 1818 by Khaled Al Awadi_compresse...
2. RBI.pptx202029291023i38039013i92292992
Modern Advanced Accounting in Canada, 9th Edition by Darrell Herauf, Murray H...
International Financial Management, 9th Edition, Cheol Eun, Bruce Resnick Tuu...
Simple linear regression model an important topic in econometrics
Chapterrrrrrrrrrrrrrrrrrrrrrrrr 2_AP.pdf
Machine Learning (ML) is a branch of Artificial Intelligence (AI)
ANALYZE MARKET DEMAND, MARKET SUPPLY AND MARKET.pptx
Relevant Information & Alternative Choice Decisions
Lesson Environment and Economic Growth.pptx
PROFITS AND GAINS OF BUSINESS OR PROFESSION 2024.pptx
USS pension Report and Accounts 2025.pdf
Very useful ppt for your banking assignments BANKING.pptx.pdf
Project_finance_introduction in finance.ppt
Group Presentation Development Econ and Envi..pptx
The Impact of Remote Work on Employee Productivity
01 KEY PROVISIONS on NGPA and PROFESSIONALIZATION.pdf
Financial discipline for educational purpose
In July, the Business Activity Recovery Index Worsened Again - IER Survey
Ad

TYPESCRIPT.pdfgshshhsjajajsjsjjsjajajjajjj

  • 2. WHAT IS TYPESCRIPT? • TypeScript is an open-source, object-oriented language developed and maintained by Microsoft, licensed under Apache 2 license. • It was introduced by Anders Hejlsberg, a core member of the development team of C# language. • TypeScript extends JavaScript by adding data types, classes, and other object-oriented features with type-checking. It is a typed superset of JavaScript that compiles to plain JavaScript.
  • 3. WHAT IS TYPESCRIPT? • TypeScript is the ES6 version of JavaScript with some additional features. • TypeScript uses TSC (TypeScript Compiler) compiler, which convert Typescript code (.ts file) to JavaScript (.js file).
  • 4. Typescript Features • Cross-Platform • Object-Oriented Language • Static type-checking • Optional Static Typing • DOM Manipulation • ES 6 Features
  • 5. TypeScript vs. JavaScript TypeScript JavaScript TypeScript is a heavy weight and strongly typed object oriented compile language which is developed by Microsoft. JavaScript on other hand is a light weight interpreted language and is introduced by Netscape. Internal implementation of TypeScript does not allow it to be used at server side. It can only be used at client side. JavaScript can be used both at client side and server side. For binding the data at code level TypeScript uses concepts like types and interfaces to describe data being used. No such concepts has been introduced in JavaScript.
  • 6. Typescript vs. JavaScript TypeScript JavaScript Code written in TypeScript first need to get compiled and then converted to JavaScript this process of conversion is known as Trans-piled. No compilation is needed in case of JavaScript. TypeScript gives support for modules hence allows the modular programming. JavaScript does not support modules and hence do not allow the modular programming. Any number of optional parameters are allowed in function code written in TypeScript. JavaScript does not support optional parameter function.
  • 7. First Program var message = "HelloWorld"; console.log(message); Output: HelloWorld //FileName: filename.ts
  • 8. TypeScript Types [Keyword] [Variable Name]: [Data Type] = [Value]; OR [Keyword] [Variable Name]: [Data Type]; • [Keyword]: var, let or const to define the scope and usage of variable. • [Data Type]: number, string, boolean, etc. var uname : string = “Sunita Rathod"; // string var age : number= 44; // number var isUpdated : boolean = true; // boolean
  • 9. Type Annotations Example: Type Annotation of Parameters function display(id:number, name:string) { console.log("Id = " + id + ", Name = " + name); } Example: Type Annotation in Object var employee : { id: number; name: string; }; employee = { id: 100, name : "John" }
  • 10. TypeScript - Variable • TypeScript follows the same rules as JavaScript for variable declarations. • Variables can be declared using: var, let, and const. Example: Variable Declaration using let let employeeName = "John"; // or let employeeName:string = "John";
  • 11. Advantages of let over var • Block-scoped let variables cannot be read or written to before they are declared. Example: let vs var console.log(num1); // Compiler Error: error TS2448: Block-scoped variable 'num' used before its declaration let num1:number = 10 ; console.log(num2); // OK, Output: undefined var num2:number = 10 ;
  • 12. Advantages of let over var • Let variables cannot be re-declared Example: Multiple Variables with the Same Name var num:number = 1; // OK var Num:number = 2; // OK var NUM:number = 3; // OK var NuM:number = 4; // OK let num:number = 5; // Compiler Error: Cannot redeclared block-scoped variable 'num' let Num:number = 6; // Compiler Error: Cannot redeclared block-scoped variable 'Num' let NUM:number = 7; // Compiler Error: Cannot redeclared block-scoped variable 'NUM' let NuM:number = 8; // Compiler Error: Cannot redeclared block-scoped variable 'NuM'
  • 14. Const • The const makes a variable a constant where its value cannot be changed. Example: Const Variable const num:number = 100; num = 200; //Compiler Error: Cannot assign to 'num' because it is a constant or read-only property const num:number; //Compiler Error: const declaration must be initialized num = 100;
  • 16. Number Example: TypeScript Number Type Variables let first:number = 123; // number let second: number = 0x37CF; // hexadecimal let third:number=0o377 ; // octal let fourth: number = 0b111001; // binary console.log(first); // 123 console.log(second); // 14287 console.log(third); // 255 console.log(fourth); // 57
  • 17. String • String values are surrounded by single quotation marks or double quotation marks. Example: TypeScript String Type Variable let employeeName:string = 'John Smith'; //OR let employeeName:string = "John Smith";
  • 18. Boolean • Boolean values are supported by both JavaScript and TypeScript and stored as true/false values. Example: TypeScript String Type Variable let isPresent:boolean = true;
  • 19. Void • void is used where there is no data. • For example, if a function does not return any value then you can specify void as return type. Example: void function sayHi(): void { console.log('Hi!') } let speech: void = sayHi(); console.log(speech); //Output: undefined
  • 20. Null vs. Undefined SN Null Undefined 1. It is an assignment value. It can be assigned to a variable which indicates that a variable does not point any object. It is not an assignment value. It means a variable has been declared but has not yet been assigned a value. 2. It is an object. It is a type itself. 3. The null value is a primitive value which represents the null, empty, or non-existent reference. The undefined value is a primitive value, which is used when a variable has not been assigned a value. 4. Null indicates the absence of a value for a variable. Undefined indicates the absence of the variable itself. 5. Null is converted to zero (0) while performing primitive operations. Undefined is converted to NaN while performing primitive operations.
  • 21. Never • TypeScript introduced a new type never, which indicates the values that will never occur. Example: never function throwError(errorMsg: string): never { throw new Error(errorMsg); } function keepProcessing(): never { while (true) { console.log('I always does something and never ends.') } }
  • 22. Arrays • An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax. • let fruits: string[] = ['Apple', 'Orange', 'Banana']; • let fruits: Array<string> = ['Apple', 'Orange', 'Banana']; • let arr = [1, 3, 'Apple', 'Orange', 'Banana', true, false];
  • 23. Tuples • Tuple can contain two values of different data types. Example: Tuple vs Other Data Types var empId: number = 1; var empName: string = "Steve"; // Tuple type variable var employee: [number, string] = [1, "Steve"];
  • 24. Accessing Tuple Elements • We can access tuple elements using index, the same way as an array. An index starts from zero. Example: Accessing Tuple var employee: [number, string] = [1, "Steve"]; employee[0]; // returns 1 employee[1]; // returns "Steve"
  • 25. Add Elements into Tuple • You can add new elements to a tuple using the push() method. Example: push() var employee: [number, string] = [1, "Steve"]; employee.push(2, "Bill"); console.log(employee); //Output: [1, 'Steve', 2, 'Bill']
  • 26. Enum • enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values. • There are three types of enums: 1. Numeric enum 2. String enum 3. Heterogeneous enum Example: Numeric Enum enum PrintMedia { Newspaper, Newsletter, Magazine, Book }
  • 27. Union • TypeScript allows us to use more than one data type for a variable or a function parameter. • This is called union type. Syntax: (type1 | type2 | type3 | .. | typeN) Example: Union let code: (string | number); code = 123; // OK code = "ABC"; // OK code = false; // Compiler Error
  • 28. Any • TypeScript has type-checking and compile-time checks. However, we do not always have prior knowledge about the type of some variables, especially when there are user- entered values from third party libraries. • In such cases, we need a provision that can deal with dynamic content. The Any type comes in handy here. Example: Any let something: any = "Hello World!"; something = 23; something = true;
  • 29. Type Inference in TypeScript • TypeScript infers types of variables when there is no explicit information available in the form of type annotations. • Types are inferred by TypeScript compiler when: • Variables are initialized • Default values are set for parameters • Function return types are determined For example, var a = "some text"; var b = 123; a = b; // Compiler Error: Type 'number' is not assignable to type 'string'
  • 30. Operators in TypeScript • In TypeScript, an operator can be classified into the following ways. • Arithmetic operators : (+, -, *, /, %, ++, --) • Comparison (Relational) operators : (<, >, <=, >=, ==, !=) • Logical operators : ( &&, ||, !) • Bitwise operators : (&, |, ^, ~, >>, <<, >>>) • Assignment operators : (=, +=, -=, *=, /=, %=) • Ternary/conditional operator : ( condition ? True : false) • Concatenation operator : ( + ) • Type Operator
  • 32. Decision Making in TypeScript if statement if…else statement
  • 33. Decision Making in TypeScript Switch Statement
  • 34. Loops in TypeScript • We can classify the loops into two types: • Indefinite • Definite
  • 35. Indefinite Loop While loop Do while loop
  • 39. Have a nice day
  • 40. Functions in TypeScript • Functions are the fundamental building block of any applications in JavaScript. • It makes the code readable, maintainable, and reusable. • We can use it to build up layers of abstraction, mimicking classes, information hiding, and modules.
  • 41. Function Aspects Function declaration function functionName( [arg1, arg2, ...argN] ); Function definition function functionName( [arg1, arg2, ...argN] ){ //code to be executed } Function call FunctionName();
  • 42. Function creation • We can create a function in two ways. These are: 1. Named Functions 2. Anonymous Function
  • 43. Function creation 1. Named Function Syntax: functionName( [arguments] ) { } Example: //Function Definition function display() { console.log("Hello WebX.0!"); } //Function Call display(); // Hello WebX.0!
  • 44. Function creation 2. Anonymous Function 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)); // 5
  • 45. Function Parameters Example: Function Parameters function Greet(greeting: string, name: string ) : string { return greeting + ' ' + name + '!’; } Greet('Hello','Steve');//OK, returns "Hello Steve!" Greet('Hi'); // Compiler Error: Expected 2 arguments, but got 1. Greet('Hi','Bill','Gates'); //Compiler Error: Expected 2 arguments, but got 3.
  • 46. Optional Parameters • Example: Optional Parameter function Greet(greeting: string, name?: string ) : string { return greeting + ' ' + name + '!’; } Greet('Hello','Steve');//OK, returns "Hello Steve!" Greet('Hi'); // OK, returns "Hi undefined!". Greet('Hi','Bill','Gates');//Compiler Error: Expected 2 arguments, but got 3.
  • 47. TypeScript Arrow Function • It omits the function keyword. • We can call it fat arrow (=>) • It is also called as Lambda function. • The arrow function has lexical scoping of "this" keyword Syntax: (parameter1, parameter2, ..., parameterN) => expression;
  • 48. TypeScript Arrow function Arrow function with Parameter let sum = (x: number, y: number): number => { return x + y; } console.log(sum(10, 20)); Output : 30
  • 49. TypeScript Arrow function Arrow function without a parameter let Print = () => console.log("Hello TypeScript"); Print(); Output: Hello TypeScript
  • 50. Function overloading • TypeScript provides the concept of function overloading. • You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same. • Function overloading is also known as method overloading.
  • 51. Function Overloading • Advantages of function overloading 1. It saves the memory space so that program execution becomes fast. 2. It provides code reusability, which saves time and efforts. 3. It increases the readability of the program. 4. Code maintenance is easy.
  • 52. Classes and Objects • In object-oriented programming languages like Java and C#, classes are the fundamental entities used to create reusable components. • TypeScript introduced classes to avail the benefit of object-oriented techniques like encapsulation and abstraction. • The class in TypeScript is compiled to plain JavaScript functions by the TypeScript compiler to work across platforms and browsers.
  • 53. Classes and Objects • A class definition can contain the following properties: 1. Fields: It is a variable declared in a class. 2. Methods: It represents an action for the object. 3. Constructors: It is responsible for initializing the object in memory. 4. Nested class and interface: It means a class can contain another class.
  • 54. Classes and Objects Syntax to declare a class A class keyword is used to declare a class in TypeScript. We can create a class with the following syntax: class <class_name>{ field; method; } Object Creation Syntax: let object_name = new class_name(parameter)
  • 55. Object Initialization • Object initialization means storing of data into the object. • There are three ways to initialize an object. These are: 1. By Reference Variable 2. By Method 3. By Constructor
  • 56. Inheritance • Inheritance is the ability of a program to create a new class from an existing class. • It is a mechanism which acquires the properties and behaviors of a class from another class. • The class whose members are inherited is called the base class, and the class that inherits those members is called the derived/ child/ subclass.
  • 57. Inheritance • In child class, we can override or modify the behaviors of its parent class. • The TypeScript uses class inheritance through the extends keyword. • TypeScript supports only single inheritance and multilevel inheritance. It doesn't support multiple and hybrid inheritance. • We can use inheritance for Method Overriding (so runtime polymorphism can be achieved) and code reusability.
  • 58. Interfaces • An Interface is a structure which acts as a contract in our application. • It defines the syntax for classes to follow. • We cannot instantiate the interface, but it can be referenced by the class object that implements it. • The interface contains only the declaration of the methods and fields, but not the implementation.
  • 59. Interfaces Syntax: interface interface_name { // variables' declaration // methods' declaration }
  • 60. Modules • A module is a way to create a group of related variables, functions, classes, and interfaces, etc. • It executes in the local scope, not in the global scope. • We can create a module by using the export keyword and can use in other modules by using the import keyword. • Modules import another module by using a module loader.
  • 61. Modules • The most common modules loaders which are used in JavaScript are the CommonJS module loader for Node.js and require.js for Web applications. • Steps: 1. Module Creation 2. Accessing the module in another file by using the import keyword. 3. Compiling and Execution of Modules
  • 62. Modules Example: Let us understand the module with the following example. 1. Module Creation //FileName: addition.ts export class Addition{ constructor(private x: number, private y: number){ } Sum(){ console.log("SUM: " +(this.x + this.y)); } }
  • 63. Modules 2. Accessing the module in another file by using the import keyword. //FileName: app.ts import {Addition} from './addition'; let addObject = new Addition(10, 20); addObject.Sum();
  • 64. Modules 3. Compiling and Execution of Modules Open the terminal and go to the location where you stored your project. Now, type the following command in the terminal window. $ tsc --module commonjs app.ts $ node ./app.js Output: SUM: 30
  • 65. Have a nice day