SlideShare a Scribd company logo
 Installing TypeScript, Basics of TypeScript
 Function, Parameter Types and Return Types, Arrow
Function
 Function Types, Optional and Default Parameters, Rest
Parameter
 Creating an Interface, Duck Typing, Extending Interface
 Classes, Constructor, Access Modifiers, Properties and
Methods
 Creating and using Namespaces, Creating and using
Modules
 Module Formats and Loaders, Module Vs Namespace
 What is Generics, What are Type Parameters
 Generic Functions, Generic Constraints
UNIT - IV Typescript
TypeScript
 TypeScript is a syntactic superset of JavaScript which
adds static typing.This basically means that TypeScript adds
syntax on top of JavaScript, allowing developers to
add types.
 In JavaScript, function parameters and variables don't have
any information! So developers need to look at
documentation, or guess based on the implementation.
 TypeScript allows specifying the types of data being passed
around within the code, and has the ability to report errors
when the types don't match.
 TypeScript is transpiled into JavaScript using a compiler.
 TypeScript has an official compiler which can be installed
through npm.
 To install Typescript,we have two ways:
1.Install typescript using Nodejs Package manager(npm).
2.Install Typescript plug in your IDE
 Installing Typescript:
Firstly we need to install nodejs and then install
typescript.After installing nodejs,check whether it is installed
completely or not on cmd.
$node –v
$npm –v
Now install the typescript using the following commands:
$ npm install typescript --save-dev //As dedependency
$ npm install typescript -g //Install as a global
module
$ npm install typescript@latest -g //Install latest if you
have an oldeversion
 TypeScript cannot run directly on the browser. It needs
a compiler to compile the file and generate it in
JavaScript file, which can run directly on the browser.
 The TypeScript source file is in ".ts" extension. We can
use any valid ".js" file by renaming it to ".ts" file.
 TypeScript uses TSC (TypeScript Compiler) compiler,
which convert Typescript code (.ts file) to JavaScript
(.js file)
 To check whether the installation was completed or not.
$tsc –v
 To run a typescript program:
Step 1 : Create a file with extension .ts
Step 2 : Compile the code using the command: tsc
filename.ts
Now it will create a nodejs file
Step 3 : Now compile the js file using command : node
filename.js
File1.ts:
function greeter(person) {
return "Hello, " + person;
}
let user = 'Meanstack';
console.log(greeter(user));
Function:
 Functions are the most crucial aspect of JavaScript as it is
a functional programming language. Functions are pieces
of code that execute specified tasks.
 They are used to implement object-oriented
programming principles like classes, objects,
polymorphism, and abstraction. It is used to ensure the
reusability and maintainability of the program. Although
TypeScript has the idea of classes and modules, functions
are still an important aspect of the language.
 Function declaration: The name, parameters, and return
type of a function are all specified in a function
declaration.
 The function declaration has the following:
 Function definition:It includes statements that will be
executed.It outlines what should be done and how it
should be done.The function definition has the following
Syntax:
 Function call:A function can be called from anywhere in
the application.In both function calling and function
definition,the parameters/arguments must be same.We
msut pass the same number fo parameters that the function
definition specifies.
Function Types
Types of Functions in TypeScript: There are two types of
functions in TypeScript:
 Named function: A named function is defined as one that is
declared and called by its given name. They may include
parameters and have return types. Syntax: functionName(
[args] ) { }
 Anonymous Function: An anonymous function is a function
without a name. At runtime, these kinds of functions are
dynamically defined as an expression. We may save it in a
variable and eliminate the requirement for function names.
Syntax: let result = function( [args] ) { }
File.ts:
function multiply(a: number, b: number) {
return a * b;
}
console.log(multiply(2,5))
Output:
Advantage of function:
 Code Reusability: We can call a function several times without
having to rewrite the same code block. The reusability of code
saves time and decreases the size of the program.
 Less coding: Our software is more concise because of the
functions. As a result, we don’t need to write a large number of
lines of code each time we execute a routine activity.
 Easy to debug: It makes it simple for the programmer to
discover and isolate incorrect data.
 Return Type The type of the value returned by the function can
be explicitly defined.
File.ts:
function getTime(): number {
return new Date().getTime();
}
console.log(getTime());
Output:
 Void Return Type The type void can be used to indicate a
function doesn't return any value.
Program:
function printHello(): void {
console.log('Hello!');
}
printHello();
Output:
Parameters
 Function parameters are typed with a similar syntax as
variable declarations.
Program:
function multiply(a: number, b: number) {
return a * b;
}
console.log(multiply(2,5))
Output:
 Optional Parameters:By default TypeScript will assume all
parameters are required, but they can be explicitly marked as
optional.
Program:
function add(a: number, b: number, c?: number) {
return a + b + (c || 0);
}
console.log(add(2,5))
Output:
Arrow function
 ES6 version of TypeScript provides an arrow function
which is the shorthand syntax for defining the anonymous
function, i.e., for function expressions. It omits the function
keyword.
 We can call it fat arrow (because -> is a thin arrow and =>
is a "fat" arrow). It is also called a Lambda function. The
arrow function has lexical scoping of "this" keyword.
 The motivation for arrow function is:
•When we don't need to keep typing function.
•It lexically captures the meaning of this keyword.
•It lexically captures the meaning of arguments.
 Syntax:
(parameter1, parameter2, ..., parameterN) => expression;
•Parameters: A function may or may not have parameters.
•The arrow notation/lambda notation (=>)
•Statements: It represents the function's instruction set.
Example:
let sum = (a, b) => {
return a + b;
};
console.log(sum(20, 30));
Output:
 Default Parameters:For parameters with default values, the
default value goes after the type annotation:
Program:
function pow(value: number, exponent: number = 10) {
return value ** exponent;
}
console.log(pow(10));
Output:
 Named Parameters Typing named parameters follows the same
pattern as typing normal parameters.
Program:
function divide({ dividend, divisor }: { dividend: number,
divisor: number }) {
return dividend / divisor;
}
console.log(divide({dividend: 10, divisor: 2}));
Output:
 Rest Parameters Rest parameters can be typed like normal
parameters, but the type must be an array as rest
parameters are always arrays.
Program:
function add(a: number, b: number, ...rest: number[]) {
return a + b + rest.reduce((p, c) => p + c, 0);
}
console.log(add(10,10,10,10,10));
Output:
INTERFACE:
 The TypeScript compiler uses interface for type-checking
(also known as "duck typing" or "structural subtyping")
whether the object has a specific structure or not.
 The interface contains only the declaration of the methods and
fields, but not the implementation. We cannot use it to build
anything. It is inherited by a class, and the class which
implements interface defines all members of the interface.
 Interface Declaration:We can declare an interface as below.
Interface interface_name {
// variables' declaration
// methods' declaration
}
 An interface is a keyword which is used to declare a
TypeScript Interface.An interface_name is the name of the
interface.An interface body contains variables and methods
declarations.
Program:
interface OS {
name: String;
language: String;
}
let OperatingSystem = (type: OS): void => {
console.log('Android ' + type.name + ' has ' +
type.language + ' language.');
};
let Oreo = {name: 'O', language: 'Java'}
OperatingSystem(Oreo);
Output:
Classes:
 In object-oriented programming languages like Java, classes
are the fundamental entities which are used to create reusable
components. It is a group of objects which have common
properties.
 In terms of OOPs, a class is a template or blueprint for
creating objects. It is a logical entity.
 A class definition can contain the following properties:
o Fields: It is a variable declared in a class.
o Methods: It represents an action for the object.
o Constructors: It is responsible for initializing the
object in memory.
o Nested class and interface: It means a class can
contain another class.
 TypeScript is an Object-Oriented JavaScript language, so it
supports object-oriented programming features like classes,
interfaces, polymorphism, data-binding, etc. JavaScript ES5 or
earlier version did not support classes. TypeScript support this
feature from ES6 and later version.
 TypeScript has built-in support for using classes because it is
based on ES6 version of JavaSript. Today, many developers
use class-based object-oriented programming languages and
compile them into JavaScript, which works across all major
browsers and platforms.
 Declaring of a class:
class <class_name>{
field;
method;
}
Program:
class Person {
name: string;
}
const person = new Person();
person.name = "Meanstack";
console.log(person);
Output:
Creating an object of class
 A class creates an object by using the new keyword
followed by the class name. The new keyword allocates
memory for object creation at runtime. All objects get
memory in heap memory area. We can create an object as
below.
 Syntax:
let object_name = new class_name(parameter)
1. new keyword: it is used for instantiating the object in
memory. 2. The right side of the expression invokes the
constructor, which can pass values.
Example
//Creating an object or instance
let obj = new Student(); )
Program:
var Car = (function () {
//constructor
function Car(engine) {
this.engine = engine;
}
Car.prototype.disp = function () {
console.log("Function displays Engine is : " + this.engine);
};
return Car;
}());
var obj = new Car("Ford");
console.log("Reading attribute value Engine as : " + obj.engine);
obj.disp();
Output:
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
Example:
//Creating an object or instance
let obj = new Student();
//Initializing an object by reference variable
obj.id = 101;
obj.name = "Virat Kohli";
2. By method
A method is similar to a function used to expose the behavior of
an object. Advantage of Method
o Code Reusability
o Code Optimization
Program:
//Defining a Student class.
class Student {
//defining fields
id: number;
name:string;
//creating method or function
display():void {
console.log("Student ID is: "+this.id)
console.log("Student ID is: "+this.name)
}
}
//Creating an object or instance
let obj = new Student();
obj.id = 101;
obj.name = "Priya";
obj.display();
Output:
3. By Constructor
A constructor is used to initialize an object. In TypeScript, the
constructor method is always defined with the name
"constructor." In the constructor, we can access the member of
a class by using this keyword.
Example:
//defining constructor
constructor(id: number, name:string) {
this.id = id;
this.name = name;
}
Extending Interfaces
Interfaces can extend each other's definition. Extending an interface
means you are creating a new interface with the same properties as
the original, plus something new.
Program:
interface Rectangle {
height: number,
width: number
}
interface ColoredRectangle extends Rectangle {
color: string
}
const coloredRectangle: ColoredRectangle = {
height: 20,
width: 10,
color: "red"
};
Output:
Access Modifiers
 TypeScript Access Modifiers Like other programming
languages, Typescript allows us to use access modifiers at the
class level. It gives direct access control to the class member.
These class members are functions and properties. We can use
class members inside its own class, anywhere outside the class,
or within its child or derived class.
 The access modifier increases the security of the class
members and prevents them from invalid use. We can also use
it to control the visibility of data members of a class. If the
class does not have to be set any access modifier, TypeScript
automatically sets public access modifier to all class members
The TypeScript access modifiers are of three types.
These are:
1. Public
2. Private
3. Protected
1.Public
In TypeScript by default, all the members (properties and
methods) of a class are public. So, there is no need to prefix
members with this keyword. We can access this data member
anywhere without any restriction.
Example:
class Student {
public studCode: number;
studName: string;
}
let stud = new Student();
stud.studCode = 101;
stud.studName = "Priya";
console.log(stud.studCode+ " "+stud.studName);
Output:
2.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.
Example:
class Student {
public studCode: number;
private studName: string;
constructor(code: number, name: string){
this.studCode = code;
this.studName = name;
}
public display() {
return (`My unique code: ${this.studCode}, my
name: ${this.studName}.`);
}
}
let student: Student = new Student(101, "Priya");
console.log(student.display());
Output:
3.Protected
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.
Example:
class Student {
public studCode: number;
protected studName: string;
constructor(code: number, name: string){
this.studCode = code;
this.studName = name;
}
}
class Person extends Student {
private department: string;
constructor(code: number, name: string, department: string) {
super(code, name);
this.department = department;
}
public getElevatorPitch() {
return (`My unique code: ${this.studCode}, my name:
${this.studName} and I am in ${this.
department} Branch.`);
} }
let joeRoot: Person = new Person(101, "Priya", "CSE");
console.log(joeRoot.getElevatorPitch());
Output:
Namespaces
 The namespace is a way which is used for logical grouping
of functionalities. It encapsulates the features and objects
that share common relationships.
 It allows us to organize our code in a much cleaner way. A
namespace is also known as internal modules.
 A namespace can also include interfaces, classes, functions,
and variables to support a group of related functionalities.
Unlike JavaScript, namespaces are inbuilt into TypeScript.
 In JavaScript, the variables declarations go into the global
scope. If the multiple JavaScript files are used in the same
project, then there will be a possibility of confusing new
users by overwriting them with a similar name.
 Hence, the use of TypeScript namespace removes the
naming collisions.
namespace {
export interface I1 { }
export class c1{ }
}
 To access the interfaces, classes, functions, and variables in
another namespace, we can use the following syntax.
namespaceName.className;
 namespaceName.functionName;
If the namespace is in separate TypeScript file, then it must be
referenced by using triple-slash (///) reference syntax.
/// < reference path = "Namespace_FileName.ts" />
 Create Project and Declare files
NameSpace file: studentCalc
Program:
namespace studentCalc{
studentCalc.ts:
namespace studentCalc{
export function AnualFeeCalc(feeAmount: number,
term: number){
return feeAmount * term;
}
}
F1.ts:
/// <reference path = "./studentCalc.ts" />
let TotalFee = studentCalc.AnualFeeCalc(1500, 4);
console.log("Output: " +TotalFee);
Output:
Module
 JavaScript has a concept of modules from ECMAScript
2015. TypeScript shares this concept of a module. 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. In
other words, the variables, functions, classes, and interfaces
declared in a module cannot be accessible outside the
module directly.
 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.
 At runtime, the module loader is responsible for locating and
executing all dependencies of a module before executing it.
 The most common modules loaders which are used in
JavaScript are the CommonJS module loader for Node.js
and require.js for Web applications. We can divide the
module into two categories:
1. Internal Module
2. External Module
 Internal Module
Internal modules were in the earlier version of
Typescript. It was used for logical grouping of the classes,
interfaces, functions, variables into a single unit and can be
exported in another module. The modules are named as a
namespace in the latest version of TypeScript. So today,
internal modules are obsolete. But they are still supported by
using namespace over internal modules.
Internal Module Syntax in Earlier Version:
module Sum {
export function add(a, b) {
console.log("Sum: " +(a+b));
}
}
Internal Module Syntax from ECMAScript 2015:
namespace Sum {
export function add(a, b) {
console.log("Sum: " +(a+b));
}
}
 External Module
External modules are also known as a module. When
the applications consisting of hundreds of files, then it is
almost impossible to handle these files without a modular
approach.It is used to specify the load dependencies between
the multiple external js files.
 Module declaration : We can declare a module by using
the export keyword. The syntax for the module declaration
is given below.
//FileName : EmployeeInterface.ts
export interface Employee {
//code declarations
}
 We can use the declare module in other files by using an import
keyword, which looks like below. The file/module name is
specified without an extension.
import { class/interface name } from 'module_name’;
Example: Addition.ts
export class Addition{
constructor(private x?: number, private y?: number){
}
Sum(){
console.log("SUM: " +(this.x + this.y));
}
}
F1.ts:
import {Addition} from './addition';
let addObject = new Addition(10, 20);
addObject.Sum();
Module vs Namespace
Typescript language extension of java script
Generics
 Generics allow creating 'type variables' which can be used to
create classes, functions & type aliases that don't need to
explicitly define the types that they use.
 Generics provides type safety without compromising the
performance, or productivity. TypeScript uses generics with
the type variable which denotes types. The type of generic
functions is just like non-generic functions, with the type
parameters listed first, similarly to function declarations.
 In generics, we need to write a type parameter between
the open (<) and close (>) brackets, which makes it strongly
typed collections. Generics use a special kind of type
variable <T> that denotes types. The generics collections
contain only similar types of objects.
Advantage of Generics
1.Type-safety: We can hold only a single type of objects in
generics. It doesn't allow to store other objects.
2.Typecasting is not required: There is no need to typecast
the object.
3.Compile-Time Checking: It is checked at compile time so
the problem will not occur at runtime.
Example:
function identity(arg) {
return arg;
}
var output1 = identity("Typescript");
var output2 = identity(101);
console.log(output1);
console.log(output2);
 Generics with functions help make more generalized
methods which more accurately represent the types used
and returned.
Example:
function createPair<S, T>(v1: S, v2: T): [S, T] {
return [v1, v2];
}
console.log(createPair<string, number>('typescript',101));
Output:
Output:
 Generics can be used to create generalized classes,
like Map.
 Generics in type aliases allow creating types that are
more reusable.
Example:(for class)
class NamedValue<T> {
private _value: T | undefined;
constructor(private name: string) {}
public setValue(value: T) {
this._value = value;
}
public getValue(): T | undefined {
return this._value;
}
public toString(): string {
return `${this.name}: ${this._value}`;
}
}
const value = new
NamedValue<number>('myNumber');
value.setValue(10);
console.log(value.toString()); // myNumber: 10
Output:

More Related Content

PDF
C++ Files and Streams
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
PPT
Singly link list
PPTX
Introduction to Turing Machine
PPTX
Object Oriented Programming using C++(UNIT 1)
PPTX
Recursive Function
PPSX
Files in c++
C++ Files and Streams
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Singly link list
Introduction to Turing Machine
Object Oriented Programming using C++(UNIT 1)
Recursive Function
Files in c++

What's hot (20)

PPTX
2D Array
PPTX
Ppt on Linked list,stack,queue
PDF
Constructors and destructors
PPTX
Conversion of Infix to Prefix and Postfix with Stack
PPT
Structure and Enum in c#
PPTX
Java swing
PPTX
Inorder traversal
PPTX
pointers,virtual functions and polymorphism
PDF
Algorithm Specification and Data Abstraction
PPTX
PPTX
Pointers in C Programming
PPTX
Nested loops
PPT
Files in c++ ppt
PPTX
Functions in c++
PDF
Python programming : Classes objects
PDF
Constructors and destructors
PPTX
tree Data Structures in python Traversals.pptx
PDF
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
PPTX
Presentation on c structures
PPTX
Arrays in C++
2D Array
Ppt on Linked list,stack,queue
Constructors and destructors
Conversion of Infix to Prefix and Postfix with Stack
Structure and Enum in c#
Java swing
Inorder traversal
pointers,virtual functions and polymorphism
Algorithm Specification and Data Abstraction
Pointers in C Programming
Nested loops
Files in c++ ppt
Functions in c++
Python programming : Classes objects
Constructors and destructors
tree Data Structures in python Traversals.pptx
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
Presentation on c structures
Arrays in C++
Ad

Similar to Typescript language extension of java script (20)

PPTX
Getting started with typescript
PPTX
OOC MODULE1.pptx
PDF
Type script
PPTX
Functions and Header files ver very useful
PPTX
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
RTF
over all view programming to computer
PDF
Tutorial basic of c ++lesson 1 eng ver
DOCX
C# Unit 1 notes
PPTX
Functions.pptx, programming language in c
PDF
.NET Portfolio
PPTX
c & c++ logic building concepts practice.pptx
PPTX
C Programming Unit-1
DOCX
Let's us c language (sabeel Bugti)
PPTX
Interoduction to c++
PPT
U19CS101 - PPS Unit 4 PPT (1).ppt
PPTX
Notes(1).pptx
DOCX
csharp.docx
PPT
iOS Application Development
PPTX
Programming in C FUNCTION Basic concepts.pptx
Getting started with typescript
OOC MODULE1.pptx
Type script
Functions and Header files ver very useful
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
over all view programming to computer
Tutorial basic of c ++lesson 1 eng ver
C# Unit 1 notes
Functions.pptx, programming language in c
.NET Portfolio
c & c++ logic building concepts practice.pptx
C Programming Unit-1
Let's us c language (sabeel Bugti)
Interoduction to c++
U19CS101 - PPS Unit 4 PPT (1).ppt
Notes(1).pptx
csharp.docx
iOS Application Development
Programming in C FUNCTION Basic concepts.pptx
Ad

More from michaelaaron25322 (14)

PPT
computer-system-architecture-morris-mano-220720124304-fefd641d.ppt
PPTX
Python programming language introduction unit
PPTX
memory Organization in computer organization
PPTX
EST is a software architectural style that was created to guide the design an...
PPTX
Spring data jpa are used to develop spring applications
PPTX
Python programming language introduction unit
PPTX
Unit-II AES Algorithm which is used machine learning
PPT
UNIT2_NaiveBayes algorithms used in machine learning
PPTX
Spring Data JPA USE FOR CREATING DATA JPA
PPTX
Computer organization algorithms like addition and subtraction and multiplica...
PPTX
mean stack
PPT
karnaughmaprev1-130728135103-phpapp01.ppt
PPT
booleanalgebra-140914001141-phpapp01 (1).ppt
PPTX
mst_unit1.pptx
computer-system-architecture-morris-mano-220720124304-fefd641d.ppt
Python programming language introduction unit
memory Organization in computer organization
EST is a software architectural style that was created to guide the design an...
Spring data jpa are used to develop spring applications
Python programming language introduction unit
Unit-II AES Algorithm which is used machine learning
UNIT2_NaiveBayes algorithms used in machine learning
Spring Data JPA USE FOR CREATING DATA JPA
Computer organization algorithms like addition and subtraction and multiplica...
mean stack
karnaughmaprev1-130728135103-phpapp01.ppt
booleanalgebra-140914001141-phpapp01 (1).ppt
mst_unit1.pptx

Recently uploaded (20)

PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Construction Project Organization Group 2.pptx
PPTX
web development for engineering and engineering
PPT
Project quality management in manufacturing
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Welding lecture in detail for understanding
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
CYBER-CRIMES AND SECURITY A guide to understanding
Lesson 3_Tessellation.pptx finite Mathematics
UNIT 4 Total Quality Management .pptx
Model Code of Practice - Construction Work - 21102022 .pdf
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Lecture Notes Electrical Wiring System Components
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
OOP with Java - Java Introduction (Basics)
Construction Project Organization Group 2.pptx
web development for engineering and engineering
Project quality management in manufacturing
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
bas. eng. economics group 4 presentation 1.pptx
Welding lecture in detail for understanding
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Arduino robotics embedded978-1-4302-3184-4.pdf

Typescript language extension of java script

  • 1.  Installing TypeScript, Basics of TypeScript  Function, Parameter Types and Return Types, Arrow Function  Function Types, Optional and Default Parameters, Rest Parameter  Creating an Interface, Duck Typing, Extending Interface  Classes, Constructor, Access Modifiers, Properties and Methods  Creating and using Namespaces, Creating and using Modules  Module Formats and Loaders, Module Vs Namespace  What is Generics, What are Type Parameters  Generic Functions, Generic Constraints UNIT - IV Typescript
  • 2. TypeScript  TypeScript is a syntactic superset of JavaScript which adds static typing.This basically means that TypeScript adds syntax on top of JavaScript, allowing developers to add types.  In JavaScript, function parameters and variables don't have any information! So developers need to look at documentation, or guess based on the implementation.  TypeScript allows specifying the types of data being passed around within the code, and has the ability to report errors when the types don't match.  TypeScript is transpiled into JavaScript using a compiler.  TypeScript has an official compiler which can be installed through npm.
  • 3.  To install Typescript,we have two ways: 1.Install typescript using Nodejs Package manager(npm). 2.Install Typescript plug in your IDE  Installing Typescript: Firstly we need to install nodejs and then install typescript.After installing nodejs,check whether it is installed completely or not on cmd. $node –v $npm –v Now install the typescript using the following commands: $ npm install typescript --save-dev //As dedependency $ npm install typescript -g //Install as a global module $ npm install typescript@latest -g //Install latest if you have an oldeversion
  • 4.  TypeScript cannot run directly on the browser. It needs a compiler to compile the file and generate it in JavaScript file, which can run directly on the browser.  The TypeScript source file is in ".ts" extension. We can use any valid ".js" file by renaming it to ".ts" file.  TypeScript uses TSC (TypeScript Compiler) compiler, which convert Typescript code (.ts file) to JavaScript (.js file)  To check whether the installation was completed or not. $tsc –v
  • 5.  To run a typescript program: Step 1 : Create a file with extension .ts Step 2 : Compile the code using the command: tsc filename.ts Now it will create a nodejs file Step 3 : Now compile the js file using command : node filename.js File1.ts: function greeter(person) { return "Hello, " + person; } let user = 'Meanstack'; console.log(greeter(user));
  • 6. Function:  Functions are the most crucial aspect of JavaScript as it is a functional programming language. Functions are pieces of code that execute specified tasks.  They are used to implement object-oriented programming principles like classes, objects, polymorphism, and abstraction. It is used to ensure the reusability and maintainability of the program. Although TypeScript has the idea of classes and modules, functions are still an important aspect of the language.  Function declaration: The name, parameters, and return type of a function are all specified in a function declaration.  The function declaration has the following:
  • 7.  Function definition:It includes statements that will be executed.It outlines what should be done and how it should be done.The function definition has the following Syntax:  Function call:A function can be called from anywhere in the application.In both function calling and function definition,the parameters/arguments must be same.We msut pass the same number fo parameters that the function definition specifies.
  • 8. Function Types Types of Functions in TypeScript: There are two types of functions in TypeScript:  Named function: A named function is defined as one that is declared and called by its given name. They may include parameters and have return types. Syntax: functionName( [args] ) { }  Anonymous Function: An anonymous function is a function without a name. At runtime, these kinds of functions are dynamically defined as an expression. We may save it in a variable and eliminate the requirement for function names. Syntax: let result = function( [args] ) { } File.ts: function multiply(a: number, b: number) { return a * b; } console.log(multiply(2,5))
  • 9. Output: Advantage of function:  Code Reusability: We can call a function several times without having to rewrite the same code block. The reusability of code saves time and decreases the size of the program.  Less coding: Our software is more concise because of the functions. As a result, we don’t need to write a large number of lines of code each time we execute a routine activity.  Easy to debug: It makes it simple for the programmer to discover and isolate incorrect data.
  • 10.  Return Type The type of the value returned by the function can be explicitly defined. File.ts: function getTime(): number { return new Date().getTime(); } console.log(getTime()); Output:  Void Return Type The type void can be used to indicate a function doesn't return any value.
  • 11. Program: function printHello(): void { console.log('Hello!'); } printHello(); Output: Parameters  Function parameters are typed with a similar syntax as variable declarations. Program: function multiply(a: number, b: number) { return a * b; } console.log(multiply(2,5))
  • 12. Output:  Optional Parameters:By default TypeScript will assume all parameters are required, but they can be explicitly marked as optional. Program: function add(a: number, b: number, c?: number) { return a + b + (c || 0); } console.log(add(2,5)) Output:
  • 13. Arrow function  ES6 version of TypeScript provides an arrow function which is the shorthand syntax for defining the anonymous function, i.e., for function expressions. It omits the function keyword.  We can call it fat arrow (because -> is a thin arrow and => is a "fat" arrow). It is also called a Lambda function. The arrow function has lexical scoping of "this" keyword.  The motivation for arrow function is: •When we don't need to keep typing function. •It lexically captures the meaning of this keyword. •It lexically captures the meaning of arguments.  Syntax: (parameter1, parameter2, ..., parameterN) => expression;
  • 14. •Parameters: A function may or may not have parameters. •The arrow notation/lambda notation (=>) •Statements: It represents the function's instruction set. Example: let sum = (a, b) => { return a + b; }; console.log(sum(20, 30)); Output:
  • 15.  Default Parameters:For parameters with default values, the default value goes after the type annotation: Program: function pow(value: number, exponent: number = 10) { return value ** exponent; } console.log(pow(10)); Output:  Named Parameters Typing named parameters follows the same pattern as typing normal parameters.
  • 16. Program: function divide({ dividend, divisor }: { dividend: number, divisor: number }) { return dividend / divisor; } console.log(divide({dividend: 10, divisor: 2})); Output:  Rest Parameters Rest parameters can be typed like normal parameters, but the type must be an array as rest parameters are always arrays.
  • 17. Program: function add(a: number, b: number, ...rest: number[]) { return a + b + rest.reduce((p, c) => p + c, 0); } console.log(add(10,10,10,10,10)); Output:
  • 18. INTERFACE:  The TypeScript compiler uses interface for type-checking (also known as "duck typing" or "structural subtyping") whether the object has a specific structure or not.  The interface contains only the declaration of the methods and fields, but not the implementation. We cannot use it to build anything. It is inherited by a class, and the class which implements interface defines all members of the interface.  Interface Declaration:We can declare an interface as below. Interface interface_name { // variables' declaration // methods' declaration }  An interface is a keyword which is used to declare a TypeScript Interface.An interface_name is the name of the interface.An interface body contains variables and methods declarations.
  • 19. Program: interface OS { name: String; language: String; } let OperatingSystem = (type: OS): void => { console.log('Android ' + type.name + ' has ' + type.language + ' language.'); }; let Oreo = {name: 'O', language: 'Java'} OperatingSystem(Oreo); Output:
  • 20. Classes:  In object-oriented programming languages like Java, classes are the fundamental entities which are used to create reusable components. It is a group of objects which have common properties.  In terms of OOPs, a class is a template or blueprint for creating objects. It is a logical entity.  A class definition can contain the following properties: o Fields: It is a variable declared in a class. o Methods: It represents an action for the object. o Constructors: It is responsible for initializing the object in memory. o Nested class and interface: It means a class can contain another class.
  • 21.  TypeScript is an Object-Oriented JavaScript language, so it supports object-oriented programming features like classes, interfaces, polymorphism, data-binding, etc. JavaScript ES5 or earlier version did not support classes. TypeScript support this feature from ES6 and later version.  TypeScript has built-in support for using classes because it is based on ES6 version of JavaSript. Today, many developers use class-based object-oriented programming languages and compile them into JavaScript, which works across all major browsers and platforms.  Declaring of a class: class <class_name>{ field; method; }
  • 22. Program: class Person { name: string; } const person = new Person(); person.name = "Meanstack"; console.log(person); Output:
  • 23. Creating an object of class  A class creates an object by using the new keyword followed by the class name. The new keyword allocates memory for object creation at runtime. All objects get memory in heap memory area. We can create an object as below.  Syntax: let object_name = new class_name(parameter) 1. new keyword: it is used for instantiating the object in memory. 2. The right side of the expression invokes the constructor, which can pass values. Example //Creating an object or instance let obj = new Student(); )
  • 24. Program: var Car = (function () { //constructor function Car(engine) { this.engine = engine; } Car.prototype.disp = function () { console.log("Function displays Engine is : " + this.engine); }; return Car; }()); var obj = new Car("Ford"); console.log("Reading attribute value Engine as : " + obj.engine); obj.disp();
  • 25. Output: 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 Example: //Creating an object or instance let obj = new Student(); //Initializing an object by reference variable obj.id = 101; obj.name = "Virat Kohli";
  • 26. 2. By method A method is similar to a function used to expose the behavior of an object. Advantage of Method o Code Reusability o Code Optimization Program: //Defining a Student class. class Student { //defining fields id: number; name:string; //creating method or function display():void { console.log("Student ID is: "+this.id) console.log("Student ID is: "+this.name) } }
  • 27. //Creating an object or instance let obj = new Student(); obj.id = 101; obj.name = "Priya"; obj.display(); Output:
  • 28. 3. By Constructor A constructor is used to initialize an object. In TypeScript, the constructor method is always defined with the name "constructor." In the constructor, we can access the member of a class by using this keyword. Example: //defining constructor constructor(id: number, name:string) { this.id = id; this.name = name; }
  • 29. Extending Interfaces Interfaces can extend each other's definition. Extending an interface means you are creating a new interface with the same properties as the original, plus something new. Program: interface Rectangle { height: number, width: number } interface ColoredRectangle extends Rectangle { color: string } const coloredRectangle: ColoredRectangle = { height: 20, width: 10, color: "red" };
  • 30. Output: Access Modifiers  TypeScript Access Modifiers Like other programming languages, Typescript allows us to use access modifiers at the class level. It gives direct access control to the class member. These class members are functions and properties. We can use class members inside its own class, anywhere outside the class, or within its child or derived class.  The access modifier increases the security of the class members and prevents them from invalid use. We can also use it to control the visibility of data members of a class. If the class does not have to be set any access modifier, TypeScript automatically sets public access modifier to all class members
  • 31. The TypeScript access modifiers are of three types. These are: 1. Public 2. Private 3. Protected
  • 32. 1.Public In TypeScript by default, all the members (properties and methods) of a class are public. So, there is no need to prefix members with this keyword. We can access this data member anywhere without any restriction. Example: class Student { public studCode: number; studName: string; } let stud = new Student(); stud.studCode = 101; stud.studName = "Priya"; console.log(stud.studCode+ " "+stud.studName);
  • 33. Output: 2.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. Example: class Student { public studCode: number; private studName: string; constructor(code: number, name: string){ this.studCode = code; this.studName = name; }
  • 34. public display() { return (`My unique code: ${this.studCode}, my name: ${this.studName}.`); } } let student: Student = new Student(101, "Priya"); console.log(student.display()); Output:
  • 35. 3.Protected 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. Example: class Student { public studCode: number; protected studName: string; constructor(code: number, name: string){ this.studCode = code; this.studName = name; } } class Person extends Student { private department: string;
  • 36. constructor(code: number, name: string, department: string) { super(code, name); this.department = department; } public getElevatorPitch() { return (`My unique code: ${this.studCode}, my name: ${this.studName} and I am in ${this. department} Branch.`); } } let joeRoot: Person = new Person(101, "Priya", "CSE"); console.log(joeRoot.getElevatorPitch()); Output:
  • 37. Namespaces  The namespace is a way which is used for logical grouping of functionalities. It encapsulates the features and objects that share common relationships.  It allows us to organize our code in a much cleaner way. A namespace is also known as internal modules.  A namespace can also include interfaces, classes, functions, and variables to support a group of related functionalities. Unlike JavaScript, namespaces are inbuilt into TypeScript.  In JavaScript, the variables declarations go into the global scope. If the multiple JavaScript files are used in the same project, then there will be a possibility of confusing new users by overwriting them with a similar name.  Hence, the use of TypeScript namespace removes the naming collisions.
  • 38. namespace { export interface I1 { } export class c1{ } }  To access the interfaces, classes, functions, and variables in another namespace, we can use the following syntax. namespaceName.className;  namespaceName.functionName; If the namespace is in separate TypeScript file, then it must be referenced by using triple-slash (///) reference syntax. /// < reference path = "Namespace_FileName.ts" />  Create Project and Declare files NameSpace file: studentCalc Program: namespace studentCalc{
  • 39. studentCalc.ts: namespace studentCalc{ export function AnualFeeCalc(feeAmount: number, term: number){ return feeAmount * term; } } F1.ts: /// <reference path = "./studentCalc.ts" /> let TotalFee = studentCalc.AnualFeeCalc(1500, 4); console.log("Output: " +TotalFee);
  • 41. Module  JavaScript has a concept of modules from ECMAScript 2015. TypeScript shares this concept of a module. 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. In other words, the variables, functions, classes, and interfaces declared in a module cannot be accessible outside the module directly.  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.  At runtime, the module loader is responsible for locating and executing all dependencies of a module before executing it.
  • 42.  The most common modules loaders which are used in JavaScript are the CommonJS module loader for Node.js and require.js for Web applications. We can divide the module into two categories: 1. Internal Module 2. External Module  Internal Module Internal modules were in the earlier version of Typescript. It was used for logical grouping of the classes, interfaces, functions, variables into a single unit and can be exported in another module. The modules are named as a namespace in the latest version of TypeScript. So today, internal modules are obsolete. But they are still supported by using namespace over internal modules.
  • 43. Internal Module Syntax in Earlier Version: module Sum { export function add(a, b) { console.log("Sum: " +(a+b)); } } Internal Module Syntax from ECMAScript 2015: namespace Sum { export function add(a, b) { console.log("Sum: " +(a+b)); } }
  • 44.  External Module External modules are also known as a module. When the applications consisting of hundreds of files, then it is almost impossible to handle these files without a modular approach.It is used to specify the load dependencies between the multiple external js files.  Module declaration : We can declare a module by using the export keyword. The syntax for the module declaration is given below. //FileName : EmployeeInterface.ts export interface Employee { //code declarations }  We can use the declare module in other files by using an import keyword, which looks like below. The file/module name is specified without an extension. import { class/interface name } from 'module_name’;
  • 45. Example: Addition.ts export class Addition{ constructor(private x?: number, private y?: number){ } Sum(){ console.log("SUM: " +(this.x + this.y)); } } F1.ts: import {Addition} from './addition'; let addObject = new Addition(10, 20); addObject.Sum();
  • 48. Generics  Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use.  Generics provides type safety without compromising the performance, or productivity. TypeScript uses generics with the type variable which denotes types. The type of generic functions is just like non-generic functions, with the type parameters listed first, similarly to function declarations.  In generics, we need to write a type parameter between the open (<) and close (>) brackets, which makes it strongly typed collections. Generics use a special kind of type variable <T> that denotes types. The generics collections contain only similar types of objects.
  • 49. Advantage of Generics 1.Type-safety: We can hold only a single type of objects in generics. It doesn't allow to store other objects. 2.Typecasting is not required: There is no need to typecast the object. 3.Compile-Time Checking: It is checked at compile time so the problem will not occur at runtime. Example: function identity(arg) { return arg; } var output1 = identity("Typescript"); var output2 = identity(101); console.log(output1); console.log(output2);
  • 50.  Generics with functions help make more generalized methods which more accurately represent the types used and returned. Example: function createPair<S, T>(v1: S, v2: T): [S, T] { return [v1, v2]; } console.log(createPair<string, number>('typescript',101)); Output: Output:
  • 51.  Generics can be used to create generalized classes, like Map.  Generics in type aliases allow creating types that are more reusable. Example:(for class) class NamedValue<T> { private _value: T | undefined; constructor(private name: string) {} public setValue(value: T) { this._value = value; } public getValue(): T | undefined { return this._value; } public toString(): string { return `${this.name}: ${this._value}`;
  • 52. } } const value = new NamedValue<number>('myNumber'); value.setValue(10); console.log(value.toString()); // myNumber: 10 Output: