Class Tutorial of TypeScript:

Like all other object-oriented programming languages, the TypeScript class is also the blueprint for creating objects with specific functions. A class encapsulated the data for its object. In javascript es5 have or earlier have not the concept of classes, The concept of classes is started on typescript es6.

How to create a class in typescript:

To create a class in typescript type the keyword class and then the name of the class and is good practice to use the first character or latter in upper case to declare a class, and after declaring the class name provide all the method, constructer, and propertied inside a curly bracket, the starting and ending curly bracket is the area of the declared class.

A variable inside a class is called property and a function inside a class is called method.

Example of TypeScript Class
class Person{
	firstname:string = '';
	lastname:string = '';

	constructor(firstname, lastname){
		this.firstname = firstname;
		this.lastname = lastname;
	}

	name():string{
		let fullname:string = this.firstname + ' ' + this.lastname;
		return fullname;
	}

	describePerson():string{
		let desc_person:string = 'The name is: ' + this.name();
		return desc_person;
	}
}

Note: You could go to the tutorial of function to understand how a methos is working and can go to the veriable portion to understand how properties are working.

Create an object

to create an object take a variable name to store the object data and then after equal sign uses the new keyword and then the class name you wish to create an object for and then after bracket you can pass some arguments if needed.
Below is an example of object creation of the above class:

var person_obj = new Person("Code", "Mystery");

Access the properties and methods of a class using the object.

To access the data of a class you have to write the object and then the property name or the method name followed by a dot symbol. The dot called the period is used to access the data members of the class.

Example of accessing a class property:
var person_first_name : person_obj.firstname;
console.log('The first name of the person is: ' + person_first_name);
Another example of accessing the property
var person_last_name : person_obj.lastname;
console.log('The last name of the person is: ' + person_last_name);
Example of accessing the method of a class:
var persons_name = person_obj.name();
console.log('Name of the person: ' + persons_name);
Another example to access another method
var persons_description = person_obj.describePerson();
console.log('Description of the person: ' + persons_description);

Class Inheritance:

Typescript also supports the inheritance, that is using typescript ye can create a new class using another class. The class from which extends another class is called parent class or superclass and the class where the superclass is extending is called child class or subclass.
To declare a class extended from another class first we have to declare a class and then the superclass name is separated by keyword extends.
in the below example we are going to extend from class Person which is declared above.

Example:
class Employee extends Person{
	depertment:string = '';

	constructor(firstname, lastname, depertment){
		super(firstname, lastname);
		this.depertment = depertment;
	}

	employeeDescription(){
		let emp_description:string = 'My name is ' + super.name() + ' and my department is ' + this.depertment;
		return emp_description; 
	}
}

Note: you can see that the data we are inheriting from the superclass has not been declared inside the subclass and fetching the data which is exist in the super class, by super prefix seperated by dot insted of this prefix.

Creating an object of a subclass

It’s similar to creating an object of sub-class as like super class but here we have to pass the parameters of super class also to get the proper result.

Example:
let emp_obj = new Employee('Code','Mystery','Developer');

Access a method of a subclass

method access for the subclass is also similar to the superclasses method access which is described above.

Example:
let emp_desc = emp_obj.employeeDescription();
console.log(emp_desc);

Multiple Inheritance:

A superclass can be extended from multiple classes. As we have extended person class in employee class and we can create another class also and extends the superclass Person there also.
For example, we are going to create another class student where we are going to extende the super class person.

Example:
class Student extends Person{
	course:string = '';
	constructor(firstname, lastname, course){
		super(firstname);
		super(lastname);
		this.course = course;
	}

	studentDescription(){
		let students_description = 'My name is ' + super.name() + ' and my course is ' + this.course;
		return students_description;
	}
}

Note here you can see that we have extended Person class in employee class and in Student class also. and have used the property first name and last name from super class.

Creat object
let std_obj = new Student('Code','Mystery','Engineering');
let std_desc = std_obj.studentDescription();
console.log(std_desc);

Multi-Level Inheritance:

we can inherit a class into a sub-class and also can inherit the sub-class into another sub-class is called multi-level inheritance.
In the below example, we are going to create another class EmpAttandence which will extend the class Employee and in this case, the Employee class has already extended a class name Person.

Example:
class EmpAttandence extends Employee{
	attendence:string = '';

	constructor(firstname, lastname, depertment, attendence){
		super(firstname, lastname, depertment);
		this.attendence = attendence;
	}

	employeeAttendence(){
		let emp_attendence:string = super.employeeDescription() + ' and my attendance is: ' + this.attendence;
		return emp_attendence; 
	}
}

Creating object

to create an object for the multi-level inheritance we have to pass all the parameters required.

Example:
var empattendence_obj = new EmpAttandence('Code','Mystery','Developer','22 Days');
var emp_attendence = empattendence_obj.employeeAttendence();
console.log(emp_attendence);

Method Overriding:

The method overriding is the ability to redefine the method by chield class of parent class.

Example:
class People{
	printData(){
		console.log('Its the data log of parrent');
	}
}

class Man extends People{
	printData(){
		super.printData();
		console.log('Its the data log of chield');
	}
}

var man_obj = new Man();
var prntdta = man_obj.printData();

Here we can see that both the methods data will be printed. so here the chield classes method is overriding the parent’s classes method.

Static Keyword:

A static variable can retain its data until the program finished its execution, A static keyword can be declared inside a class as a member variable and to call the static variable or get the value we have to refer to it by class name.

Example:
class StaticExample{
	static a_num:number;

	static displayVal():void{
		console.log("The value of num is"+ StaticExample.a_num);
	}
}
StaticExample.a_num = 12     
StaticExample.displayVal() 

Here we are initialized the data first and then invoke the static method.

instanceof Operator.

The instenceof operator is used to check and returns true if the object belongs to a particular specified type

Example:
class SampleClass{ } 
var smple_cls_obj = new SampleClass() 
var isSampleClass = smple_cls_obj instanceof SampleClass; 
console.log("If the object is an instance of SampleClass " + isSampleClass);

Encapsulation or Data Hiding:

There is a visibility control option for data members to member to other classes called Data Hiding or Encapsulation.
We can make a data hiding procedure by using Access Specifier, A Access Specifier provide permission if a data member can be visible from the outside of the class or not.

There are 3 types of Access Specifiers and they are as described below.

  1. public: A public type data member has universal access, that is the data can be accessed from outside of the class also, by default a data member is public if not defined by any access specifier
  2. private: A private data member has accessibility only on the members which are defined inside the same class.
  3. protected: A protected data member has accessibility on the members which are defined inside the same class and also have the access from its chield classes.
Example:
class SampleEncapsulation { 
   a_str:string = "Code"; 
   private second_str:string = "Mystery"; 
}
 
var smpl_encpltn_obj = new SampleEncapsulation() ;
console.log(smpl_encpltn_obj.a_str);
console.log(smpl_encpltn_obj.second_str);

Here we can see that the public property is accessible from the outside of the class but the private property is throwing errors while compiling.

The interface of Classes:

Like extends we can use the implements keyword to make an interface. Now suppose the same property name exists in the parent class and child class, Then binding the property on chield classes called an interface.

Example:
interface ASampleInterface { 
   sample_num:number; 
} 

class ASampleClass implements ASampleInterface { 
   sample_num:number; 
   sample_num2:number; 
   
   constructor(sample_num:number,sample_num2:number) { 
      this.sample_num = sample_num; 
      this.sample_num2 = sample_num2; 
   } 
} 

var aclass_obj = new ASampleClass(10,12) ;
console.log("First Number is : "+aclass_obj.sample_num+" Second Number is : "+aclass_obj.sample_num2 );

Note here we have to provide the same variable name and data type located inside the interface in the classes where the interface is implemented.

Share The Post On -

Add a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.