Classes and Objects in Typescript| Constructor and Inheritance examples

In this tutorial, you’ll learn the fundamentals of classes and objects in the TypeScript programming language.

In Any Object-Oriented Programming paradigm, the foundational elements are classes and objects. Classes store the data, while the behavior or methods operating on it are represented by methods.

You can also check out Typescript final keyword.

What is a Class in TypeScript?

Class was introduced in the ES6 version of JavaScript and has also been implemented in TypeScript. A class acts as a model or template for newly created objects.

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

A Class Contains the Following:

  • Properties or member variables
  • Constructor
  • Methods

How to Declare a Class with Members in TypeScript

A class can be created using the class keyword. It contains properties/variables/members to hold data, methods that operate on data (which can be general methods or setters and getters), and a constructor used to initialize object data.

Below is TypeScript code for a class declaration:

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

The generated JavaScript code is

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

In the above example, we’ve created the Employee class with a name property variable. We provided a constructor and returned the name object using a getter.

How to Create an Object in TypeScript

There are several ways to create objects for each class. Each object has unique properties and data manipulated by methods. The new keyword operator is used to allocate memory space for an object.

Here is an example of creating objects

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

In the above example, two objects called emp1 and emp2 are created, each with a different name property.

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 to initialize instance members during object creation. These are optional and similar to JavaScript functions in TypeScript.

An Employee object is created using the new operator. During object creation, the constructor is called to initialize member variables.

class Base {
  length: number;
  width: number;

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

In the object hierarchy, you can extend the parent class using the extends keyword. In the constructor method, you have to call the super() method to invoke the superclass constructor.

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

TypeScript Class Inheritance

Inheritance is an object-oriented concept used to reuse all properties and methods of the superclass object.

You can create a class that extends the superclass and define your behavior. This allows for code 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 the parent or super or base class.
  • The Lion class is the child or subclass or derived class.
  • We defined the parent class as Animal and the child as Lion class which extends the parent class.
  • If the constructor is declared in the child class, the first call is to the superclass constructor
  • using the super keyword. Otherwise, it throws a compilation error constructors for derived classes must contain a ‘super’ call
  • You can also define and add class properties in your child class.

Abstract Class in TypeScript

Abstract classes are like regular classes except they contain abstract methods.

Abstract methods are methods that have only a declaration without implementation. An implementation needs to be provided by classes that extend abstract classes.

Abstract Class Features

  • These classes contain either abstract methods or method implementations.
  • They cannot be created as objects 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 Modifiers

In TypeScript, different accessor types can be applied to instance members, variables, properties, and methods: public, private, protected, Readonly.

public modifier: If a variable is declared without a modifier, the compiler treats it as public by default. This can be applied to variable declarations 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 variables or arguments in the constructor and are private to the class. Variables or methods declared as private have the following accessibility rules.

  • Can be used within the class.
  • Cannot be accessed in derived classes.
  • Cannot be accessed outside of the class.
  • The object of the class is not accessible.

protected modifier: The protected modifier has the following accessibility rules:

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

Readonly modifier:

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

Class Static Properties

TypeScript supports the static keyword for properties of a class. If you want to maintain the same properties for all objects of a class, you can use a static declaration for properties.

Here’s an example of static variable declaration:

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

Summary

We’ve learned about class types in TypeScript, including access modifiers and examples, as well as declaring static keywords.