TypeScript
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'];
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]);
ageMapping.set("Rakesh", 40);
ageMapping.set("Abhishek", 25);
ageMapping.set("Amit", 30);
//Add Values
studentEntries.add("John");
studentEntries.add("Peter");
studentEntries.add("Gayle");
studentEntries.add("Kohli");
studentEntries.add("Dhawan");
class Student {
public studCode: number;
studName: string;
}
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}.`);
}
}
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
// 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) { }
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;
//defining constructor
constructor(id: number, name:string) {
this.id = id;
this.name = name;
}
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.
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
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