Unit 3 TypeScript.pptx
Unit 3 TypeScript.pptx
What is TypeScript?
TypeScript is a strongly typed, object-oriented, compiled
programming language that builds on JavaScript.
It is a superset of the JavaScript language.
It allows us to use strict types.
Supports modern features like arrow functions, let, const etc.
Extra features like generics, interfaces, tuples etc.
You can install the TypeScript compiler into your system by
using npm.
npm install -g typescript
TypeScript compiles into simple JavaScript.
The TypeScript compiler is also implemented in TypeScript and
can be used with any browser or JavaScript engines like
Node.js.
How to use TypeScript?
TypeScript code is written in a file with .ts extension and then
compiled into JavaScript using the TypeScript compiler.
A TypeScript file can not be executed directly. First it is
converted into JavaScript and then the js file get executed.
The command tsc <filename>.ts compiles the TypeScript code
into a plain JavaScript file.
tsc app.ts
JavaScript files can then be included in the HTML and run on
any browser.
TypeScript
tsc app.ts JavaScript
File (app.ts) File (app.js)
Features of TypeScript?
Object Oriented Programming Language: TypeScript provides
support for OOPs concepts like Classes, Interfaces, Inheritance,
etc.
Compilation: TypeScript compiler provides the feature of error
checking. If there is a syntax error in the code, then TypeScript
will generate a compilation error so that the error could get
highlighted before runtime.
Strong Static Typing: TypeScript has the feature of strong static
typing which comes through TLS(TypeScript language service).
Supports JavaScript Libraries: As it is a superset of JavaScript,
all the libraries and existing JavaScript code are valid
TypeScript code as well.
Features of TypeScript?
Portable: TypeScript is portable as the code written in
TypeScript can be run on any browser or operating system. It
can run in any environment in which JavaScript can run.
JavaScript is TypeScript: Code written in JavaScript with a .js
extension can be converted to TypeScript by changing the
extension from .js to .ts.
DOM Manipulation: We can make use of TypeScript to handle
DOM for adding or removing elements.
Code Readability: Its code is written using classes and
interfaces. They provide organization to the program and
therefore it is easy to maintain and debug the code.
Components of TypeScript
TypeScript has three main components:
○ Language: The syntax, keywords, and type annotations.
○ The TypeScript Compiler (TSC): Converts the instructions
written in TypeScript to its JavaScript equivalent.
○ The TypeScript Language Service: An additional layer of
editor-like applications, such as statement completion,
signature help, code formatting, converting of variable to
specific type.
Compiling TypeScript
Open the starter resource in visual studio code resource
Create a TypeScript file inside the starter folder and write some
ts code.
app.ts file app.js file
var title = "This is ts
const title = "This is ts
session";
session";
var inputs =
const inputs =
document.querySelectorAll("i
document.querySelectorAll tsc app.ts nput");
("input");
inputs.forEach(function (el)
inputs.forEach((el) => {
{
console.log(el);
console.log(el);
});
});
We can also use -w with command for automatic Get-ExecutionPolicy -List
compilation on file save tsc app.ts -w Set-ExecutionPolicy RemoteSigned
Set-ExecutionPolicy Restricted
Data Types in TypeScript
Primitive types available in TypeScript are boolean, bigint, null,
number, string, symbol, undefined, any (allow anything),
unknown (ensure someone using this type declares what the
type is), never (it’s not possible that this type could happen),
and void (a function which returns undefined or has no return
value).
We can check the type of a variable by using typeof.
Strings in ts can be in single quotes and double quotes.
TypeScript use strict types i.e if we define a variable as string
then we can not change the type of that variable.
TypeScript Array
In TypeScript we can create an array as follow:
let data = ["Abhinav", "Manoj", "Vinay", "Aman"];
Now we can not add any other type value into this array.
TypeScript will treat it as a string array.
data.push(100); Argument of type number' is not
assignable to parameter of type
If you want to add number type value to this array then assign
one integer value to this array.
let data = ["Abhinav", "Manoj", "Vinay", "Aman", 1];
data.push(100);
Now it will work fine.
TypeScript Objects
In TypeScript we can create an object
as follow: let student = {
let student = { name: "Abhi",
name: "Abhi", age: 19,
age: 19, branch: "CSE",
branch: "CSE", marks: 87,
marks: 87, };
}; // Assign different object
to this variable
We can update the property of an student = { name: "Aman",
object as: age: 21, branch: "IT",
student.age=20; marks: 85 };
We can not assign different type
value to any property.
student.name = 10; Type 'number' is not assignable
to type 'string'
TypeScript Explicit Types
// Basic types
let studentName: string; We can create a mixed type
let age: number;
let isActive: boolean;
array using union type.
// Assign value to these variables // Union type
studentName = "Aman"; let mixedArr: (string | number |
age = 20; boolean)[] = [];
// This array can contain string,
// Arrays number and boolean value
let students: string[]; // String array mixedArr.push(10);
//students.push("Ajay"); // We can not do mixedArr.push(true);
this as the array is not initialized // We can also use union type with
let studentArr: string[] = []; // String normal variables
array with initialization
studentArr.push("Ajay"); // Now We can do let input: string | number | boolean;
this
TypeScript Explicit Types
// Object
let studentOne: object;
studentOne = { name: "Akash", age: 20, gender: "Male" };
// We can assign array to this object because array is an object
studentOne = [];
// If you do not want to assign array to this object then you can use
let studentTwo: {
name: string;
age: number;
gender: string;
};
studentTwo = { name: "Aman", age: 20, gender: "Male" };
// We can not add any extra property to this variable
studentTwo = { name: "Abhay", age: 31, gender: "Male", marks: 20 };
// The above statement will not work
Dynamic any Type
let input: any;
input = 20; //number type
We use any type console.log(typeof input);
to define a input = "This is string"; //string type
console.log(typeof input);
variable that can
input = [10, "name", 30, "text"]; //array object type
contain any type console.log(input);
value in future. input.push(true);
console.log(input);
If you do not know
// Object
the type of input = {name: "Abhi", age: 15, uid: "5477567567558",
variable in city: "Noida",
};
advance then you
// any type array
can use any. let input: any[] = [];
input.push(10);
// any type object
let student: { name: any; age: any; gender: any };
TypeScript Functions
TypeScript functions can be created both as a named function
or as an anonymous function.
Named function:
function addTwoNumbers(num1: number, num2: number): number {
return num1 + num2;
}
Anonymous function:
(num1: number, num2: number): number => {
return num1 + num2;
};
Writing the Function Type
We can declare a function type variable as:
let myFun: (num1: number, num2: number, num3: number) => number;
If you do not want to return any value from a function then you
can use void
let message = (): void => {
console.log("Thsi is a function without any return value");
};
Function Overloading
TypeScript provides the concept of function overloading
In TypeScript 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.
Provide the prototype/declaration of the function
function addTwoValues(param1: string, param2: number): string;
function addTwoValues(param1: number, param2: number): number;
Provide the implementation of the function only one time
function addTwoValues(param1: any, param2: any): any {
return param1 + param2;
}
Now we can use this function as:
console.log(addTwoValues(10, 20));
console.log(addTwoValues("Test", 20));
Type Aliases in TypeScript
Type aliases is just giving another name for a type.
Aliasing doesn’t create a new type; instead, it gives that type a
new name.
Consider the following example:
let userDetail = (name: string, uid: string | number) => {
console.log(`The name is ${name} and uid is ${uid}`);
};
let anotherUserDetail = (user: {
name: string; Here the parameters are complex so we
age: number; can use type aliases
uid: string | number;
}) => {
console.log(
`The user name is ${user.name}, age is ${user.age} and uid is
${user.uid}`
);
};
Type Aliases in TypeScript
We can do type aliases in the previous code as:
type stringOrNumber = string | number;
type objUserAliases = { name: string; age: number; uid:
stringOrNumber };
Class A
Class B
Advantages of Inheritance
Example of Inheritance
class Person {
name: string; displayBasicInfo() {
uid: number; console.log(
constructor(name: string, uid: number){ `The name is ${this.name}
this.name = name; and uid is ${this.uid},
this.uid = uid; } employee id is ${this.empId}
displayBasicInfo() { and salary is
console.log(`The name is ${this.name} ${this.empSalary}`
and uid is ${this.uid}`); );
} } }
class Employee extends Person { }
empId: string; let emp = new Employee("Mukesh
empSalary: number; Singh", 647578785,
constructor(name: string, uid: number, "LNXIND00001", 57000);
empId: string, empSalary: number) { let person = new Person("Aman
super(name, uid); Verma", 8657657775);
this.empId = empId; emp.displayBasicInfo();
this.empSalary = empSalary; } person.displayBasicInfo();
Access Modifiers in TypeScript
Access modifiers are used to define the accessibility of properties
and methods.
In TypeScript we have three access modifiers:
○ Private
○ Public
○ Protected
In TypeScript, we can also define a property as read only by using
readonly keyword.
Private properties and methods are accessible only inside the
class in which they are declared.
Public properties and methods are accessible from anywhere.
Protected properties and methods are accessible only inside the
class in which they are declared and inside the derived class.
Private Access Modifiers in TypeScript
class Student { let studentOne = new
private name: string; Student("Abhi", 21);
private age: number; let studentTwo = new
constructor(name: string, age: Student("Manoj", 25);
number) { studentTwo.setName("Abhay");
this.name = name; console.log(studentOne.getName()
this.age = age; );
} console.log(studentTwo.getName()
getName() {return this.name;} );
getAge() {return this.age;}
setName(name: string) {
this.name = name; Private properties are accessible
} inside the class only.
setAge(age: number) { We can access the private
this.age = age;
} properties outside the class by
} using getter and setter.
Private Access Modifiers with Method
class Student { private getNameLength() {
private name: string; return this.name.length;
private age: number; }
constructor(name: string, age: }
number) { let studentOne = new
this.name = name; Student("Abhi", 21);
this.age = age; let studentTwo = new
} Student("Manoj", 25);
displayInfo() { studentOne.displayInfo();
let nameLength = studentTwo.displayInfo();
this.getNameLength();
console.log( Here getNameLength() method
`Student name is ${this.name} is private so we can not access
and age is ${this.age}and the name
length is ${nameLength}` this method from outside the
); class.
}
Public Access Modifiers in TypeScript
class Student { public getNameLength() {
public name: string; return this.name.length;
age: number; }
constructor(name: string, age: }
number) { let studentOne = new Student("Abhi", 21);
this.name = name; let studentTwo = new Student("Manoj", 25);
this.age = age; studentOne.displayInfo();
} console.log(studentTwo.getNameLength());
displayInfo() {
let nameLength =
this.getNameLength();
console.log( Public properties are accessible
`Student name is from anywhere.
${this.name} and age is If we do not specify any access
${this.age}and the name length is
${nameLength}` modifier with property then it is
); always public by default..
}
Protected Access Modifiers in TypeScript
class Person { displayBasicInfo() {
protected name: string; console.log(`The name is
constructor(name: string) { ${this.name} and employee id is
this.name = name; ${this.empId}`);
} }
} }
class Employee extends Person { let emp = new Employee("Mukesh
empId: string; Singh", "LNX308840");
constructor(name: string, emp.displayBasicInfo();
empId: string) {
super(name);
this.empId = empId;
} Protected properties are
accessible within the same
class and inside the child class.
Read Only Properties in TypeScript
class Person { displayBasicInfo() {
readonly name: string; console.log(`The name is
constructor(name: string) { ${this.name} and employee id is
this.name = name; ${this.empId}`);
} }
} }
class Employee extends Person { let emp = new Employee("Mukesh
empId: string; Singh", "LNX308840");
constructor(name: string, emp.name = "test";
empId: string) { emp.displayBasicInfo();
super(name);
this.empId = empId;
} If a property is read only then
you can not modify the values of
that property.
Cannot assign to 'name' because
it is a read-only property.
Static Members in TypeScript
The static members of a class class Person {
are accessed using the class static objCount: number = 0;
constructor(public name:
name and dot notation, without string, public age: number) {
creating an object. Person.objCount += 1;
The static members can be }
static displayCount() {
defined by using the keyword console.log(`The object
static. count is ${Person.objCount}`);
Static variables exist within the }
}
class context, and are not let p = new Person("Mohit", 35);
carried forward to the object of let p1 = new Person("Abhay",
the class. 30);
Person.displayCount();
Abstract Class in TypeScript
Define an abstract class in Typescript using the abstract keyword.
Abstract classes are mainly for inheritance.
We cannot create an instance of an abstract class.
An abstract class typically includes one or more abstract methods
or property declarations.
The class which extends the abstract class must define all the
abstract methods.
Abstract Class in TypeScript
abstract class Person { displayDetails(): void {
constructor(readonly name: string, console.log(
readonly age: number) {} `Employee name is
displayPersonInfo() { ${this.name}, age is ${this.age}
console.log(`Person name is and employee id is ${this.empId}`
${this.name} and age is );
${this.age}`); }
} }
abstract displayDetails(): void; let emp = new Employee("Mohit",
} 20, "te002993");
class Employee extends Person { emp.displayDetails();
constructor(
readonly name: string,
readonly age: number,
private empId: string
) {
super(name, age);
}
Interface in TypeScript
interface IsPerson {
Interfaces in TypeScript name: string;
allows us to apply certain age: number;
speak(text: string): void;
structures on a class or spend(amount: number): number;
object. }
We use interface keyword to const me: IsPerson = {
name: "Mohit",
define an interface. age: 37,
speak(text: string): void {
console.log(text);
},
spend(amount: number): number {
console.log(`Spent amount
${amount}`);
return amount;
},
};
console.log(me);
Interface with Classes in TypeScript
Use implements keyword to implement an interface.