Classes in TypeScript

classes in TypeScript have a very trivial syntax to work with. Using classes we can hide the details of properties, can define behavior in a program. Let us create a class for an Item in the shop.

Example of a class in TypeScript

//typescript_class_example.ts
class Item{
    id: number;
    cost: number;
    name: string;
//constructor function
constructor(id, name){
  this.id = id;
  this.name = name;  
  }

//getter
getCost(){
    return this.cost;
  }

//setter
setCost(cost){
    this.cost = cost;
  }
}

//creating object for a class
var pen = new Item(1201, "Pen");
pen.setCost(25);
console.log(pen.getCost());
$ tsc typescript_class_example.ts
$ node typescript_class_example.js

Now let us see the each and every part of above program. In Typescript we define a class using the class keyword which is similar to other programming languages.

class myClass{
//.....
}

Properties of a class are the valid TypeScript variables with type attached in declaration and ends with a semi colon ";".

class myClass{
  property1: number;
  property2: string;

}

Member functions are normal functions with dropped function keyword. In the above example we just has two functions a getter and setter which uses property cost.

The constructor is a function which is used to initialize properties of a class. Whenever we creates a new object, constructor initializes properties with supplied parameters.

We can create an object with new keyword in TypeScript. Do remember that when we compile a TypeScript file it generates a plain JavaScript file. If we compile above program this is generated JavaScript.

var Item = (function () {
    function Item(id, name) {
        this.id = id;
        this.name = name;
    }
    Item.prototype.getCost = function () {
        return this.cost;
    };
    Item.prototype.setCost = function (cost) {
        this.cost = cost;
    };
    return Item;
}());
var pen = new Item(1201, "Pen");
pen.setCost(25);
console.log(pen.getCost());

As we know that in JavaScript (ES5), classes are implemented using Prototypes. Even TypeScript is internally generating prototype based JS code. This abstraction allows a developer to just use plain class syntax to get things done.

JavaScript has very basic support with OOP since it is more functional and scripting. But with the ability of TypeScript we can easily implement larger systems with huge code base in a object oriented design.

Initializing parameters in a class

Some times we need to initialize the properties before hand in the class. Even though constructor can do it on the fly, we can initialize data in a class. Take this example.

 class Point{

x: number = 0;
y: number = 0;

setPointLocation(x,y){
    this.x = x;
    this.y = y;
   }
}

var point1 = new Point(); //Creates new point at Origin (0,0)
point1.setPointLocation(250,250);
console.log(point1);

This code creates a new Point object initially at the origin. Then we can move it using setPointLocation method.

Encapsulation in TypeScript

Encapsulation in TypeScript is implemented using access modifiers. These access modifiers help in protecting the variables from modification. There are three types of access modifiers for class properties.

  • Public
  • Protected
  • Private

public keyword is used before a class property to make it accessible by object. By default all properties becomes public.

class Car{
public name:string;
public chasis:number;
constructor(name,chasis_no){
    this.name = name;
    this.chasis = chasis_no;
}
}

var sedan = new Car("Hoonda", "14563");
console.log(sedan.name);

private keyword is used to hide the details from object to modify. Only internal class methods can access and modify the necessary private variables.

class Shape{
public radius: number;
private pi: number = 3.14;
constructor(radius){
    this.radius = radius;
}
area(){
        return (this.pi * this.radius * this.radius); 
}
}

var circle = new Shape(5);
console.log(circle.area());
// TypeScript compiler throws warning saying inaccesible property 
console.log(circle.pi);

In above example Shape is a class which has the radius property. Pi=3.14 is an internal variable and should not be exposed outside. So we defined it as a private property.

protected keyword is used before properties to make them visible to classes which extend the base class. All private variables will be blocked from extending by a subclass in TypeScript. We need to specify them as a special class called "protected".

class A{
  public property1: number;
  private property2: string;
  // protected variable is private to it's own object.
  protected property3: string;
}

class B extends A{
  // This class inherits property1 and property3
  // Since property2 is private B won't get it
}