Course Banner


TypeScript Class Object

TypeScript Class & Object

As you know TypeScript is superset of javascript several new features are added and Object-oriented is one of them. Since, javascript does not implement the concept of Object oriented directly, Typescript does the ask easy by allowing the developers to write code in object-oriented way and the transpiler converstes the code into native javascript code.While working on Angular , you will see that you almost cannot work on any project without classes.

So, it's important that you understand this chapter properly before proceeding with the next chapter.

If you come from Java, C++ or C# or Object oriented PHP background, understanding this chapter will be a real eas.

But if you have no idea about object-and class. I advise you to  read this chapter properly.

What is Class ?

A group of objects which has common behaviour and properties, is called class.

Object

Object is an instance of the class.


Creating classes

Use the class keyword to declare a class in TypeScript. The syntax for the same is given below −

Syntax

class class_name {
  // data member here

}

Class start with class keyword and followed by class name.

Class naming convention :

  1. Class Name cannot start with number

  2. Class Name cannot have special character

  3. Class name cannot have spaces

  4. Class Name can be  camelCase.Ex. bykeClass

  5. Cannot contain keyword. Example class class. Is wrong.

  6. Class keyword must be in lower case. ‘Class’ is wrong  ‘class’ is right

Once class is declared,Class name can have following entity.

  • Properties − The variable declared inside class is called  of that class. There can be as many as properties inside the class.

  • Constructors − Constructor is a special function  which is declared with with constructor keyword. When an object of the class is created, constructor gets called automatically.

  • Functions : functions are piece of code which are created to perform specific task. A class can contain as many functions as one likes.

So, combination of all these components are known as as the data members of the class.

Consider a class Person in typescript.

class Mammal{
}

On compiling, it will generate following JavaScript code.

var Mammal =  (function () {

  function Mammal() {

  }

  return Mammal;

}());



Example: Class and data members

class Animal {

  color:string;

  //constructor
  constructor(color:string) {
     this.color = color
  }

     walk():void {
     console.log("Color of animal is :   "+this.engine)
  }
}


In the above example, we have declared a class called Animal. Since, Animal have some attributes like color, height etc. So, here I have declared color property variable with string data type.Remember one thing that while declaring any class property, var keyword is not used.

And then we  have declared a constructor. I have already mentioned above what constructor is all about.Here you can see, constructor have parameter called color.

Also, you may have noticed above, we have used  ‘this’ keyword which refers to the current instance of the class.

We have also declared walk() i function where we  have called the color property and displayed.


On compiling, it will generate following JavaScript code.

var Animal = (function () {

  //constructor

  function Animal(color) {

      this.color = color;

  }

  Animal.prototype.walk = function () {

      console.log("Color of animal is :   " + this.color);

  };

  return Animal;

}());

As you can see, transpiler of Typescript converts our Typescript code into Javascript code. Since Javascript directly does not implement class-object, it uses prototype chaining system, the code is converted into that Javascript readable code. And this code is more complicated as compared to the class object pattern.

The benefit is that  developer does not have to worry about the internal codding and they  can focus on familiar pattern of object orientation.

Creating Instance objects

Once class is created we need to create instance of that class to access the data members of that class. ‘new’ keyword is used.

Syntax

var object name here= new class_name()

Example: Instantiating a class

var obj = new Animal("White")

Accessing Properties and Functions

As mentioned above once object is created. You can access data members of that class through that object. So in our case  we can show the property of the class called ‘color’ with .()dot operator.

Here is the example :

obj.color;

Complete Example :

class Animals {

 color:string;

 size:string;

 //constructor with arguments and default values

 constructor(height:string='Medium',appearance:string='Brown') {

    this.size = height

    this.color = appearance

 }

 //function

 walk():void {

    console.log("The animal is  : "+this.size + " "+ this.color )

 }

}


var obj = new Animals("Big")

console.log("Reading attribute value color as :  "+obj.color);

obj.walk()


console.log('================ENDS First Object================');

console.log('============Creating Object 2 ====================');

var obj2 = new Animals("Small",'White')

obj2.walk()

console.log("Reading attribute value color as :  "+obj2.color)

console.log('============Ends Object 2 ====================');


The output of the above code is as follows −


Class Inheritance

Inheritance is one of the mechanism where one or more classes inherits feature of base class with restriction or without restriction. As you have been reading since beginning of this TypeScript tutorial that TypeScript offers the concept of Inheritance.

Extends keyword is used for class inheritance. If you use extends that means  that child class is inheriting the data members of base class.

Syntax

class child_class_name extends parent_class_name

Like JAVA, Typescript also does not support multiple inheritance  because of ambiguity. But multiple inheritance is implemented other way through interface which we will cover in in next chapter.

Example: Class Inheritance

class Animals {

  constructor (public name) {  

   }

  Walk(legs) {

      console.log(this.name + " " + " Animals Walks with :" + legs +  ' legs');

  }

  Eat(live){

  }

}

class Animal1 extends Animals {

  constructor (public name) { super(name); }

  Eat(live) {

      console.log(this.name + "  "+ live + " And");

      //super.Walk(4) + "legs";

  }

}





console.log('========Super Class===========');

var one = new Animals("All")

one.Walk(4)

console.log('=========Animal 1 Details ==========');

var two: Animals = new Animal1("Dog")

two.Eat('Meat');

The output of the above code is as follows −


In the example declares a class Animals. And we have created another class called Animal1  which is inheriting class Animals. Now, all properties , methods can be accessed by class Animal1 of Animals internally.

There are following types of inheritance.

  • Single − A child class can inherit the property of base class. We hae already seen that in the above example.

  • Multiple − When child class can inherit two or more than two base class, its called multiple inheritance.Like JAVA TypeScript doesn’t support multiple inheritance.

  • Multi-level − When one class inherits the other class and the inheriting class once again is inherited by next class then its called Multilevel inheritance.

    Example of Multilevel Inheritance

class Car{

  Features(){

      return "1. All cars has four wheels";

  }

}

class Mercedez extends Car {

  constructor(){

      super();     

  }

   Features (){

      return super.Features() + " 2. But Mercedez is special car";

  }

}

class Luxury extends Mercedez {

  constructor(){

      super();               

  }

       

   Features(){

          return super.Features() + " C. and Luxury  has Artificial Intelligence";

   }

}

var c = new Luxury();

console.log(c.Features());

In the above program we have declared a class called ‘car’ and the Mercedez class extends  base class ‘Car’. And further Luxury car extends Mercedes car. All the classes have one common function called Features(). Also you may have noticed that two subclasses have super function which in turn hiddenly calls super base class constructor.

Its output is as follows −


Method Overriding

Method Overriding is a way in which  the base class redefines the superclass’s method. In this, base class and child class both have same method names. The following example illustrates the same −

class Training{

  Teach():void {

    console.log("Teach() from classroom…")

 }

}

class OnlineTraining extends Training{

 Teach():void {

    super.Teach()

    console.log("Teaching Online")

 }

}

var obj = new OnlineTraining()

obj.Teach()

In the above program you can see there are two classes. The base class name is Training. Inside that there is a method called Teach(). And then there is another class called OnlineTraining which extends base class training. Both have same method name called Teach. When object is created and called the function, by default the child class method is called first. If we need to show base class method, we have to write write super().

The static Keyword

The static keyword can be applied to the data members of a class. When we declare a data member as static variable it holds its values till the program finishes execution. To access static members  we do not have to create object.

Example

class Holder{  
  static num:number;
  
  static show():void {
     console.log("The value of num is"+ Holder.num)
  }
}

Holder.num = 100     // initialize the static variable
Holder.show()      // invoke the static method


The output of the above code is as follows −

The value of num is 100

The instanceof operator

The instanceof operator is used to check if the object is of specified type.

Example

class Student{ }

var obj = new Student()

var isSt = obj instanceof Student;

console.log(" obj is an instance of Student" + isSt);



The output of the above code is as follows −


Access  Specifiers

Access specifiers are keywords which is responsible for putting restricting the access of  data members by inheriting classes. The the data hiding is possible through these access specifiers.  

Below are the list of access specifiers or  access modifiers .

S.No.

Access Specifier & Description

1.

public

If the data members are  declared public, this means that it can accessed globally .

2.

private

If the data members are defined as private,the data members are available within that class. These data members cannot be inherited by inheriting class.

3.

protected

If the data members are declared as protected, this means that it will be available within the class as well as for inheriting class.

Example

class PrivateData {

 sname:string = "Rajesh"

 private roll:number = 45

}

var obj = new PrivateData()

console.log(obj.sname)     //accessible

console.log(obj.roll)   //compilation Error

Let us now take an example to see how data hiding works −

We have declared two variables one as public and other as private. If you don't write anything before any data member then by default it is considered  as ‘public’.

The other data member is declared as private and when that is tried to access  outside of class, it throws error.



Ad Image