Classes and Objects in Typescript| Constructor and Inheritance examples

In this tutorial, learn the basics of the classes and objects in a typescript programming language.

In Any Object-oriented programming Object-oriented programming’s foundational elements are classes and objects. The data is stored in classes, and the behavior or methods that operate on it are represented by methods. You can also check Typescript final keyword

What is Class in Typescript?

Class is introduced in the ES6 version of the latest JavaScript. The same classes were also implemented with Typescript. The class serves as a model or template for newly created objects.

A class is used to create objects of the same kind. It implies that each object contains unique data, which is then used in methods to achieve class behavior.

A Class Contains the following things

  • Properties or member variable
  • Constructor
  • Methods

How to declare a Class with members in a typescript example

The class can be created using the keyword class.

It contains

  • properties/variables/members to hold the data,
  • methods are operations done on data, These methods can be general methods or setters and getters
  • and constructor used to initialize the object data

Below is the Typescript code for the class declaration

class Employee {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  getName() {
    return name;
  }
}

Generated JavaScript code is

var Employee = /** @class */ (function () {
  function Employee(name) {
    this.name = name;
  }
  Employee.prototype.getName = function () {
    return name;
  };
  return Employee;
})();

In the above example, Created Employee class. It has a name as a property variable name and the constructor is provided, and returned the name object using a getter.

How to create an object typescript example?

There are several ways objects can be created for each class.

Each object has unique properties and data that are manipulated by methods. A new keyword operator may be used to create an object, which allocates memory space.

Here is an example of creating objects

let emp1 = new Employee("Kiran");
let emp2 = new Employee("Kiran");

In the above example, Created two objects called emp1 and emp2.

property(in this case, name) in each of these objects is different from other objects’ properties. These properties are called instance members from here onwards

Typescript Class Constructor with parameters

The constructor is used for initializing the instance members during object creation. These are optional and similar to javascript functions in typescript.

Employee object is created using the new operator. During object creation, First, the constructor is called and initializes member variables.

class Base {
  length: number;
  width: number;

  constructor(length = 10, width = 0) {
    this.length = length;
    this.width = width;
  }
}

In object hierarchy, you can extend the parent class using the extends class

In the Constructor method, You have to call the super() method to call the superclass constructor.

class Rectangle extends Base {
  length: number;
  width: number;
  constructor() {
    super();
  }
}

Typescript Class Inheritance

Inheritance is one of the object-oriented concepts which is used to reuse all the properties and methods of the superclass object.

You can create a class that can extend the superclass and can write your behavior.

This allows developers to achieve the code with reusability and maintainability. Typescript supports inheritance using the extends keyword.

class Animal {
  constructor(public isVeg: boolean, public legsCount: number) {}
  eat() {
    console.log(`eat non veg: ${this.isVeg}`);
  }
}
class Lion extends Animal {
  jump: boolean;
  constructor(public isVeg: boolean, public legsCount: number, jump: boolean) {
    super(isVeg, legsCount);
    this.jump = jump;
  }
  roars() {
    console.log("lion roars");
  }
  jumpIn() {
    console.log("lion jumps");
  }
}
let lion = new Lion(true, 4, true);
lion.roars(); //  lion roars
lion.eat(); //eat non veg: true

Notes:

  • The Animal class is called either the parent or super or base class.
  • Lion class is called either a child or subclass or derived class.
  • Defined parent class as Animal and child as Lion class which extends parent class.
  • if the constructor is declared in the child class, the First call is to call the superclass constructor -if there is a constructor in a child class that extends the parent class must call the parent class constructor using the super keyword. Otherwise, it throws compilation error constructors for derived classes must contain a ‘super’ call
  • you can also define and add class properties in your child’s class

Abstract class in typescript

Abstract classes are the same as classes except it contain abstract methods. abstract methods are methods that have only declaration without implementation. An implementation needs to be provided by the classes which extend abstract classes. Abstract class features:

  • this class contains either abstract methods and method implementation
  • These classes will not be created as an object using the new operator.
  • It is not compulsory to have abstract methods

Here is a Syntax and an Example

abstract class Shape {
  abstract area(): void;
  getName(): string {
    return "Shape";
  }
}
// Generated Javascript code
var Shape = /** @class */ (function () {
  function Shape() {}
  Shape.prototype.getName = function () {
    return "Shape";
  };
  return Shape;
})();

Typescript access modifier

In typescript, There are different types of accessor types applied to instance members or variables or properties and methods. 4 types are available - public, private, protected, Readonly

public modifier: if the variable is declared without a modifier, the compiler treats it as public by default. This can be applied to variable declaration or constructor parameters as public or for methods if required.

public or default declared variables or methods can access the variable from inside or outside of a class private modifier:

This can be applied to the variables or arguments in the constructor. These are private to the class.

A variable or method declared as private has the following accessibility rules.

  • Can be used in a class
  • Can not be used in the derived class
  • Can not be accessible outside of a class
  • The object of the class is not accessible

protected modifier: the protected modifier has the following accessible rules

  • Accessible in a declared class
  • Accessible in derived classes
  • The object of the class is not accessible

Readonly modifier:

Instance member variables can be applied to read-only modifiers. These variables are initialized either in the declaration or in the constructor only.

Class Static properties

Typescript has support for a static keyword for properties of a class.

In general, each object holds different properties of a class.

What if you want to maintain the same properties for all objects of a class?

The answer is using a static declaration for a properties

Here Static variable declaration Example.

class StaticDemo {
  static staticPropertiy = 0;
  normalProperty = 0;
  constructor() {
    StaticDemo.staticPropertiy++;
    this.normalProperty++;
  }
}
var s1 = new StaticDemo();
var s2 = new StaticDemo();
console.log(StaticDemo.staticPropertiy); // outputs 2
console.log(s1.normalProperty); // outputs 1
console.log(s1.normalProperty); // outputs 1

Summary

We have learned class types in typescript with access modifiers and examples, Declaring static keywords.