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

TypeScript

The document provides an overview of TypeScript, covering key concepts such as arrays, tuples, unions, strings, numbers, loops, enums, maps, sets, access modifiers, and functions. It includes examples of syntax and usage for each concept, illustrating how to define and manipulate data structures and types in TypeScript. Additionally, it explains function parameters, including optional, default, and rest parameters, as well as arrow functions.

Uploaded by

Sachin Chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

TypeScript

The document provides an overview of TypeScript, covering key concepts such as arrays, tuples, unions, strings, numbers, loops, enums, maps, sets, access modifiers, and functions. It includes examples of syntax and usage for each concept, illustrating how to define and manipulate data structures and types in TypeScript. Additionally, it explains function parameters, including optional, default, and rest parameters, as well as arrow functions.

Uploaded by

Sachin Chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

TypeScript

TypeScript Arrays
An array is a homogenous collection of similar type of elements which have a contiguous memory
location. An array is a user-defined data type.
let array_name[:datatype] = [val1,val2,valn..]
let fruits: string[] = ['Apple', 'Orange', 'Banana'];

2. Using a generic array type.


let array_name: Array<elementType> = [val1,val2,valn..]
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
Array Object let arr_name:datatype[] = new Array(values);
let arr:string[] = new Array("JavaTpoint","2200","Java","Abhishek");
for(var i = 0;i<arr.length;i++) {
console.log(arr[i]);
}
let arr:string[] = new Array("JavaTpoint", "2300", "Java", "Abhishek");
//Passing arrays in function
function display(arr_values:string[]) {
for(let i = 0;i<arr_values.length;i++) {
console.log(arr[i]);
}
}
//Calling arrays in function
display(arr);
1. concat() It is used to joins two arrays and returns the combined result.
2 copyWithin() It copies a sequence of an element within the array.
3. every() It returns true if every element in the array satisfies the provided testing
function.
4. fill() It fills an array with a static value from the specified start to end index.
5. indexOf() It returns the index of the matching element in the array, otherwise
-1.
6. includes() It is used to check whether the array contains a certain element or
not.
7. Join() It is used to joins all elements of an array into a string.
8. lastIndexOf() It returns the last index of an element in the array.
9. Pop() It is used to removes the last elements of the array.
10. Push() It is used to add new elements to the array.
11. reverse()It is used to reverse the order of an element in the array.
12. Shift() It is used to removes and returns the first element of an array.
13. slice() It returns the section fo an array in the new array.
14. sort() It is used to sort the elements of an array.
15. splice() It is used to add or remove the elements from an array.
TypeScript Tuples

store a collection of values of different data types in a single variable.


let tuple_name = [val1,val2,val3, ...val n];
let arrTuple = [101, "JavaTpoint", 105, "Abhishek"];
console.log(arrTuple);
Operations :-
Push()
Pop() //Tuple Declaration
let empTuple = ["JavaTpoint", 101, "Abhishek"];
//Passing tuples in function
function display(tuple_values:any[]) {
for(let i = 0;i<empTuple.length;i++) {
console.log(empTuple[i]);
}
}
//Calling tuple in function
display(empTuple);
TypeScript Union
define a variable which can have multiple types of values.
(type1 | type2 | type3 | ........ | type-n)
let value: number|string;
value = 120;
console.log("The Numeric value of a value is: "+value);
value = "Welcome to JavaTpoint";
console.log("The String value of a value is: "+value);
function display(value: (number | string))
{
if(typeof(value) === "number")
console.log('The given value is of type number.');
else if(typeof(value) === "string")
console.log('The given value is of type string.');
}
display(123);
display("ABC");
TypeScript String
let uname = new String("Hello JavaTpoint");
console.log("Message: " +uname);
console.log("Length: "+uname.length);
1. charAt() It returns the character of the given index.
2. concat() It returns the combined result of two or more string.
3. endsWith() It is used to check whether a string ends with another string.
4. includes() It checks whether the string contains another string or not.
5. indexOf() It returns the index of the first occurrence of the specified substring
from a string, otherwise returns -1.
6. lastIndexOf() It returns the index of the last occurrence of a value in the string.
7. match() It is used to match a regular expression against the given string.
8. replace()It replaces the matched substring with the new substring.
9. search() It searches for a match between a regular expression and string.
10. slice() It returns a section of a string.
11. split() It splits the string into substrings and returns an array.
12. substring() It returns a string between the two given indexes.
13. toLowerCase() It converts the all characters of a string into lower case.
14. toUpperCase() It converts the all characters of a string into upper case.
15. trim() It is used to trims the white space from the beginning and end of the string.
16. trimLeft() It is used to trims the white space from the left side of the string.
17. trimRight() It is used to trims the white space from the right side of the string.
18. valueOf() It returns a primitive value of the specified object.
TypeScript Numbers

let identifier: number = value;

toExponential() It is used to return the exponential notation in string format.


2. toFixed()It is used to return the fixed-point notation in string format.
3. toLocaleString() It is used to convert the number into a local specific representation of
the number.
4. toPrecision() It is used to return the string representation in exponential or fixed-
point to the specified precision.
5. toString() It is used to return the string representation of the number in the
specified base.
6. valueOf()
TypeScript Definite Loop

for (first expression; second expression; third expression ) {


// statements to be executed repeatedly
}
for loop
for (var val of list) { for..of loop
//statements to be executed for..in loop
}

for (var val in list) {


//statements
}
let num = 4;
let factorial = 1;
while (num >= 1) {
factorialfactorial = factorial * num;
num--;
}
console.log("The factorial of the given number is: " + factorial);

let arr = [1, 2, 3, 4, 5];

for (var val of arr) {


console.log(val);
}

let str:any = "JavaTpoint";

for (let index in str) {


console.log('Index of ${str[index]}: ${index}');
}
Enums
Enums are a new data type supported in
TypeScript. It is used to define the set of named
constants, i.e., a collection of related values.
Three types of Enums in TypeScript. These are:

TypeScript Enums
Numeric Enums
String Enums
Heterogeneous Enums
enum Direction { enum AppStatus { //hertogenous means contains
Up = 1, number & string value
Down, ACTIVE = 'Yes',
Left, INACTIVE = 1,
Right, ONHOLD = 2,
} ONSTOP = 'STOP'
console.log(Direction); }
console.log(AppStatus.ACTIVE);
console.log(AppStatus.ONHOLD);
TypeScript forEach

array.forEach(callback[, thisObject]);

var num = [5, 10, 15];


num.forEach(function (value) {
console.log(value);
});
TypeScript Map

var map = new Map();


1. map.set(key, value) It is used to add entries in the map.
2. map.get(key) It is used to retrieve entries from the map. It returns undefined if the
key does not exist in the map.
3. map.has(key) It returns true if the key is present in the map. Otherwise, it returns
false.
4. map.delete(key) It is used to remove the entries by the key.
5. map.size() It is used to returns the size of the map.
6. map.clear() It removes everything from the map.
let map = new Map();

map.set('1', 'abhishek'); console.log( "Value1= " +map.get(1) );


map.set(1, 'www.javatpoint.com'); console.log("Value2= " + map.get('1') );
map.set(true, 'bool1'); console.log( "Key is Present= " +map.has(3) );
map.set('2', 'ajay'); console.log( "Size= " +map.size );
console.log( "Delete value= " +map.delete(1) );
console.log( "New Size= " +map.size );
Iterating Map Data
let ageMapping = new Map();

ageMapping.set("Rakesh", 40);
ageMapping.set("Abhishek", 25);
ageMapping.set("Amit", 30);

//Iterate over map keys


for (let key of ageMapping.keys()) {
console.log("Map Keys= " +key);
}
//Iterate over map values
for (let value of ageMapping.values()) {
console.log("Map Values= " +value);
}
console.log("The Map Enteries are: ");
//Iterate over map entries
for (let entry of ageMapping.entries()) {
console.log(entry[0], entry[1]);
TypeScript Set

let mySet = new Set();

1. set.add(value) It is used to add values in the set.


2. set.has(value) It returns true if the value is present in the set. Otherwise, it returns
false.
3. set.delete() It is used to remove the entries from the set.
4. set.size() It is used to returns the size of the set.
5. set.clear() It removes everything from the set.
let studentEntries = new Set();

//Add Values
studentEntries.add("John");
studentEntries.add("Peter");
studentEntries.add("Gayle");
studentEntries.add("Kohli");
studentEntries.add("Dhawan");

//Returns Set data


console.log(studentEntries);

//Check value is present or not


console.log(studentEntries.has("Kohli"));
console.log(studentEntries.has(10));

//It returns size of Set


console.log(studentEntries.size);

//Delete a value from set


console.log(studentEntries.delete("Dhawan"));

//Clear whole Set


studentEntries.clear();

//Returns Set data after clear method.


console.log(studentEntries);
TypeScript Access Modifiers

class Student {
public studCode: number;
studName: string;
}

let stud = new Student();


stud.studCode = 101;
stud.studName = "Joe Root";

console.log(stud.studCode+ " "+stud.studName);


Private

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(1, "JoeRoot");


console.log(student.display());
Protected
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(1, "JoeRoot", "CS");
console.log(joeRoot.getElevatorPitch());
Readonly Modifier

We can make the properties of the class, type, or interface readonly by using the readonly modifier.
This modifier needs to be initialized at their declaration time or in the constructor.
We can also access readonly member from the outside of a class, but its value cannot be changed.
class Company {
readonly country: string = "India";
readonly name: string;

constructor(contName: string) {
this.name = contName;
}
showDetails() {
console.log(this.name + " : " + this.country);
}
}
let comp = new Company("JavaTpoint");
comp.showDetails(); // JavaTpoint : India
comp.name = "TCS"; //Error, name can be initialized only within constructo
TypeScript Accessor

In TypeScript, the accessor property provides a method to access and set the class members. It
has two methods which are given below.
1.getter 2.setter
get propName() {
// getter, the code executed on getting obj.propName
},

set propName(value) {
// setter, the code executed on setting obj.propName = value
}
class MyDrawing { set displayFullName {
length: number = 20; const parts = value.split ('');
breadth: string = 15; this.pname = firstname[0];
this.pname = firstname[1];
get rectangle() { }
return this.length * this.breadth; person displayFullName = "Abhishek Mishra"
} console.log(student);
}
console.log(new MyDrawing().square);
let passcode = "secret passcode";

class Student {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Unauthorized update of student detail!");
}
} }
let stud = new Student();
stud.fullName = "Virat Kohli";
if (stud.fullName) {
console.log(stud.fullName);
}
TypeScript Function

Functions are the fundamental building block of any applications in JavaScript

function functionName( [arg1, arg2, ...argN] ){ function display() {


//code to be executed console.log("Hello JavaTpoint!");
} }
//Function Call
display();

// Anonymous function
let myAdd = function (x: number, y: number) : number {
return x + y;
};
// Anonymous function call
console.log(myAdd(5,3));
Function parameter can be categories into the following:

Optional Parameter
Default Parameter
Rest Parameter

Optional Parameter
function function_name(parameter1[:type], parameter2[:type], parameter3 ? [:type]) { }

function showDetails(id:number,name:string,e_mail_id?:string) {
console.log("ID:", id, " Name:",name);
if(e_mail_id!=undefined)
console.log("Email-Id:",e_mail_id);
}
showDetails(101,"Virat Kohli");
showDetails(105,"Sachin","[email protected]");
Default Parameter
function function_name(parameter1[:type], parameter2[:type] = default_value) { }

function displayName(name: string, greeting: string = "Hello") : string {


return greeting + ' ' + name + '!';
}
console.log(displayName('JavaTpoint')); //Returns "Hello JavaTpoint!"
console.log(displayName('JavaTpoint', 'Hi')); //Returns "Hi JavaTpoint!".
console.log(displayName('Sachin')); //Returns "Hello Sachin!"
Rest Parameter
The rest parameter is used to pass zero or more values to a function
function function_name(parameter1[:type], parameter2[:type], ...parameter[:type]) { }
function sum(a: number, ...b: number[]): number {
let result = a;
for (var i = 0; i < b.length; i++) {
result += b[i];
}
return result;
}
let result1 = sum(3, 5);
let result2 = sum(3, 5, 7, 9);
console.log(result1 +"\n" + result2);
TypeScript Arrow function

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

// ES6: With arrow function


var getResult = (username: string, points: number): string => {
return `${ username } scored ${ points } points!`;
} Arrow function with parameter

let sum = (a, b) => { let sum = (a: number, b: number) => a + b;
return a + b; console.log("SUM: " +sum(5, 15));
};
console.log(sum(20, 30)); //returns 50
Arrow function in a class

class Student {
studCode: number;
studName: string;
constructor(code: number, name: string) {
this.studName = name;
this.studCode = code;
}
showDetail = () => console.log("Student Code: " + this.studCode + '\nStudent Name: ' +
this.studName)
}
let stud = new Student(101, 'Abhishek Mishra');
stud.showDetail();
TypeScript Function Overloading

compile time

class A
{
public foo(s: string): number;
public foo(n: number): string;
public foo(arg: any): any
{
if (typeof(arg) === 'number')
return arg.toString();
if (typeof(arg) === 'string')
return arg.length;
}
}
let obj = new A();
console.log("Result: " +obj.foo(101));
console.log("Length of String: " +obj.foo("JavaTpoint"));
TypeScript Classes
class <class_name>{
class Student { field;
//defining fields method;
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 = "Virat Kohli";
obj.display();
class Student {
//defining fields
id: number;
name:string;

//defining constructor
constructor(id: number, name:string) {
this.id = id;
this.name = name;
}

//creating method or function


display():void {
console.log("Function displays Student ID is: "+this.id)
console.log("Function displays Student ID is: "+this.name)
}
}

//Creating an object or instance


let obj = new Student(101, "Virat Kohli")

//access the field


console.log("Reading attribute value of Student as: " +obj.id,)
console.log("Reading attribute value of Student as: " +obj.name)

//access the method or function


class Car {
TypeScript Inheritance
Color:string
constructor(color:string) { class sub_class_name extends
this.Color = color super_class_name
} {
} // methods and fields
class Audi extends Car { {
Price: number
constructor(color: string, price: number) {
super(color);
this.Price = price;
}
display():void {
console.log("Color of Audi car: " +
this.Color);
console.log("Price of Audi car: " +
this.Price);
}
}
let obj = new Audi(" Black", 8500000 );
Types of Inheritance
We can classify the inheritance into the five types. These are:

Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance

class Shape {
Area:number
constructor(area:number) {
this.Area = area
}
}
class Circle extends Shape {
display():void {
console.log("Area of the circle: "+this.Area)
}
}
var obj = new Circle(320);
obj.display()
Multilevel Inheritance
class Animal {
eat():void {
console.log("Eating")
}
}
class Dog extends Animal {
bark():void {
console.log("Barking")
}
}
class BabyDog extends Dog{
weep():void {
console.log("Weeping")
}
}
let obj = new BabyDog();
obj.eat();
obj.bark();
obj.weep()
TypeScript Interface
interface interface_name {
// variables' declaration
interface Person {
// methods' declaration
name:string
}
age:number
}
interface Employee extends Person {
gender:string
empCode:number
}
let empObject = <Employee>{};
empObject.name = "Abhishek"
empObject.age = 25
empObject.gender = "Male"
empObject.empCode = 43
console.log("Name: "+empObject.name);
console.log("Employee Code: "+empObject.empCode);
// defining interface for class
Interface in class
interface Person {
firstName: string;
lastName: string;
age: number;
FullName();
GetAge();
}
// implementing the interface
class Employee implements Person {
firstName: string;
lastName: string;
age:number;
FullName() {
return this.firstName + ' ' + this.lastName;
}
GetAge() {
return this.age;
}
constructor(firstN: string, lastN: string, getAge: number) {
this.firstName = firstN;
this.lastName = lastN;
this.age = getAge;
}
}
// using the class that implements interface
let myEmployee = new Employee('Abhishek', 'Mishra', 25);
let fullName = myEmployee.FullName();
TypeScript Generics

TypeScript Generics is a tool which provides a way to create reusable components. It creates a
component that can work with a variety of data types rather than a single data type.

function identity<T>(arg: T): T {


return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>( 100 );
console.log(output1);
console.log(output2);
function getItems<T>(items : T[] ) : T[] {
return new Array<T>().concat(items);
}
let arrNumber = getItems<number>([10, 20, 30]);
let arrString = getItems<string>(["Hello", "JavaTpoint"]);
arrNumber.push(40); // Correct
arrNumber.push("Hi! Javatpoint"); // Compilation Error
arrString.push("Hello TypeScript"); // Correct
arrString.push(50); // Compilation Error
console.log(arrNumber);
console.log(arrString);
Generics Classes
class StudentInfo<T,U>
{
private Id: T;
private Name: U;
setValue(id: T, name: U): void {
this.Id = id;
this.Name = name;
}
display():void {
console.log(`Id = ${this.Id}, Name = ${this.Name}`);
}
}
let st = new StudentInfo<number, string>();
st.setValue(101, "Virat");
st.display();
let std = new StudentInfo<string, string>();
std.setValue("201", "Rohit");
std.display();
Generics Interface

interface People {
name: string
age: number
}
interface Celebrity extends People {
profession: string
}
function printName<T extends Celebrity>(theInput: T): void {
console.log(`Name: ${theInput.name} \nAge: ${theInput.age} \nProfession: $
{theInput.profession}`);
}
let player: Celebrity = {
name: 'Rohit Sharma', age: 30, profession: 'Cricket Player'
}
printName(player);
Generics Interface as Function Type

interface StudentInfo<T, U>


{
(id: T, value: U): void;
};
function studentData(id: number, value:string):void {
console.log('Id = '+ id + ', \nName = ' + value)
}
let std: StudentInfo<number, string> = studentData;
std(11, "Rohit Sharma");
TypeScript Decorators

A Decorator is a special kind of declaration that can be applied to classes, methods, accessor,
property, or parameter. Decorators are simply functions that are prefixed @expression symbol,
where expression must evaluate to a function that will be called at runtime with information about
the decorated declaration.
Class Decorators
Method Decorators
Accessor Decorators
Property Decorators
Parameter Decorators
1. Class Decorators

@sealed
class Person {
msg: string;
constructor(message: string) {
this.msg = message;
}
show() {
return "Hello, " + this.msg;
}
}
2. Method Decorators

class Item {
itemArr: Array;
constructor() {
this.itemArr = [];
}
@log
Add(item: string): void {
this.itemArr.push(item);
}
GetAll(): Array {
return this.itemArr;
}
}
3. Accessor Decorators

class Employee {
private _salary: number;
private _name: string;

@configurable(false)
get salary() { return 'Rs. ${this._salary}'; }
set salary(salary: any) { this._salary = +salary; }

@configurable(true)
get name() { return 'Sir/Madam, ${this._name}'; }
set name(name: string) { this._name = name; }
}
4. Property Decorators

class Company {
@ReadOnly
name: string = "JavaTpoint.com";
}
let comp = new Company();
comp.name = 'SSSIT.com'; // Here, we can't change company name.
console.log(comp.name); // 'JavaTpoint.com'
5. Parameter Decorators
class Person {
msg: string;
constructor(message: string) {
this.msg = message;
}
@validate
show(@required name: string) {
return "Hello " + name + ", " + this.msg;
}
}
TypeScript Date Object

let date: Date = new Date();


console.log("Date = " + date); //Date = Tue Feb 05 2019 12:05:22 GMT+0530 (IST)

You might also like