Easy Tutorial
❮ Ts Tuple Ts Object ❯

TypeScript Classes

TypeScript is object-oriented JavaScript.

Classes describe the common properties and methods of objects created from them.

TypeScript supports all object-oriented features, such as classes, interfaces, etc.

The definition of a TypeScript class is as follows:

class class_name { 
    // class scope
}

The keyword to define a class is class, followed by the class name. A class can include the following modules (class data members):

Example

Create a Person class:

class Person {
}

Compiling the above code yields the following JavaScript code:

var Person = /** @class */ (function () {
    function Person() {
    }
    return Person;
}());

Creating Class Data Members

In the following example, we declare a Car class with a field engine. The constructor initializes the engine field after the class is instantiated.

The this keyword refers to the current object instance of the class. Note that the parameter name in the constructor is the same as the field name, and this.engine refers to the class field.

We also define a method disp() within the class.

class Car { 
    // Field 
    engine: string; 

    // Constructor 
    constructor(engine: string) { 
        this.engine = engine 
    }  

    // Method 
    disp(): void { 
        console.log("Engine is : " + this.engine) 
    } 
}

Compiling the above code yields the following JavaScript code:

var Car = /** @class */ (function () {
    // Constructor 
    function Car(engine) {
        this.engine = engine;
    }
    // Method 
    Car.prototype.disp = function () {
        console.log("Engine is : " + this.engine);
    };
    return Car;
}());

Creating Instantiated Objects

We use the new keyword to instantiate class objects, with the following syntax:

var object_name = new class_name([ arguments ])

When a class is instantiated, the constructor is called, for example:

var obj = new Car("Engine 1")

Fields and methods of the class can be accessed using the dot notation:

// Accessing property
obj.field_name 

// Accessing method
obj.function_name()

Complete Example

The following example creates a Car class, then creates an object using the new keyword and accesses its properties and methods:

class Car { 
   // Field
   engine: string; 

   // Constructor
   constructor(engine: string) { 
      this.engine = engine 
   }  

   // Method
   disp(): void { 
      console.log("Engine model displayed in function : " + this.engine) 
   } 
} 

// Create an object
var obj = new Car("XXSY1")

// Access field
console.log("Engine model read : " + obj.engine)  

// Access method
obj.disp()

Compiling the above code yields the following JavaScript code:

var Car = /** @class */ (function () {
    // Constructor
    function Car(engine) {
        this.engine = engine;
    }
    // Method
    Car.prototype.disp = function () {
        console.log("Engine model displayed in function : " + this.engine);
    };
    return Car;
}());
// Create an object
var obj = new Car("XXSY1");
// Access field
console.log("Engine model read : " + obj.engine);
// Access method
obj.disp();

The output is:

Engine model read : XXSY1
Engine model displayed in function : XXSY1

Class Inheritance

TypeScript supports class inheritance, meaning we can create a new class by inheriting from an existing class. The existing class is called the parent class, and the inheriting class is called the child class.

Class inheritance uses the extends keyword. A child class cannot inherit private members (methods and properties) and the constructor of the parent class.

TypeScript supports single inheritance but not multiple inheritance. However, TypeScript supports multiple levels of inheritance (A extends B, B extends C).

The syntax is as follows:

class child_class_name extends parent_class_name

Example

Class inheritance: In this example, we create a Shape class and a Circle class that inherits from Shape. The Circle class can directly use the Area property:

class Shape { 
   Area: number 

   constructor(a: number) { 
      this.Area = a 
   } 
} 

class Circle extends Shape { 
   disp(): void { 
      console.log("Area of the circle: " + this.Area) 
   } 
}

var obj = new Circle(223); 
obj.disp()

Compiling the above code yields the following JavaScript code:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Shape = /** @class */ (function () {
    function Shape(a) {
        this.Area = a;
    }
    return Shape;
}());
var Circle = /** @class */ (function (_super) {
    __extends(Circle, _super);
    function Circle() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Circle.prototype.disp = function () {
        console.log("Area of the circle: " + this.Area);
    };
    return Circle;
}(Shape));
var obj = new Circle(223);
obj.disp();

The output is:

Area of the circle: 223

Note that a child class can only inherit from one parent class. TypeScript does not support inheriting from multiple classes, but it supports multiple levels of inheritance, as shown in the following example:

class Root { 
   str: string; 
} 

class Child extends Root {} 
class Leaf extends Child {} // Multiple inheritance, inherits from Child and Root classes

var obj = new Leaf(); 
obj.str = "hello" 
console.log(obj.str)

Compiling the above code yields the following JavaScript code:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Root = /** @class */ (function () {
    function Root() {
    }
    return Root;
}());
var Child = /** @class */ (function (_super) {
    __extends(Child, _super);
    function Child() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Child;
}(Root));
var Leaf = /** @class */ (function (_super) {
    __extends(Leaf, _super);
    function Leaf() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Leaf;
}(Child));
var obj = new Leaf();
obj.str = "hello";
console.log(obj.str);

The output is:

hello
var Leaf = (function (Child) {
    function Leaf() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return Leaf;
}(Child)); // Multiple inheritance, inherits from Child and Root classes
var obj = new Leaf();
obj.str = "hello";
console.log(obj.str);

Output:

hello
❮ Ts Tuple Ts Object ❯