×
☰ See All Chapters

TypeScript Classes

TypeScript is an object oriented programming (OOP) language which supports object oriented programming concepts inheritance, polymorphism, abstraction and encapsulation. From object oriented programming point of view, Class is like a template or blueprint from which objects are created.

What are the members of TypeScript class?

  1. Fields/Variables 

  2. Constructors 

  3. Methods 

  4. Inner class and interface 

Syntax to write a class in TypeScript

We can declare a class using class keyword as below:

class ClassName{

//constructor

//field;    

//method;    

}  

 

We can define classes in single or in maultiple ts files.

Example:

class Box {

    legth: number;

    width: number;

    constructor(legth: number, width: number) {

        this.legth = legth;

        this.width = width;

    }

    add(box: Box) {

        return new Box(this.legth + box.legth, this.width + box.width);

    }

}

When this complied to JavaScript below code is created:

var Box = /** @class */ (function () {

    function Box(legth, width) {

        this.legth = legth;

        this.width = width;

    }

    Box.prototype.add = function (box) {

        return new Box(this.legth + box.legth, this.width + box.width);

    };

    return Box;

}());

Declaring or creating Objects using new keyword in TypeScript

Declaring Objects using new involves two steps.

  • Declaring a variable. This variable does not define an object. Instead, it is simply a variable that can refer to an object. 

  • Acquiring an actual, physical copy of the object and assign it to that variable. We can do this using the new operator.  

Syntax

let variableName = new ClassName(parameter1, parameter2, ...) ;

Example

var p1 = new Box(0, 10);

var p2 = new Box(10, 20);

Accessing Members of a class in TypeSript

To access members of class variables, we will use the dot (.) operator. The dot operator links the name of the object with the name of the member. For example, to assign the width variable of box the value 100, you would use the following statement:

box.width = 100;

JavaScript also supports creating objects with the new keyword, but there are many differences between JavaScript objects and TypeScript objects. One major difference is that TypeScript objects can't be given new properties or methods. To see what this means, suppose we want to add a new property called ‘height’. After box is created, the following assignment is acceptable in JavaScript:

box.height = 30;

But in TypeScript, this causes an error: Property ‘height’ does not exist on type “Box”. If you want to add a new property, you have to define a new class.

 


All Chapters
Author