Object - Oriented Terms Supported by TypeScript


Object-oriented programming (OOP) is a popular programming paradigm that has been widely adopted in the software development industry. OOP is based on the concept of objects, which are instances of classes that encapsulate data and behaviour. TypeScript, a statically typed superset of JavaScript, is designed to support the development of large-scale applications and is also an object-oriented programming language. In this article, we will explore the object-oriented terms supported by TypeScript.

Below we discuss various object-oriented terms supported by TypeScript.

Class

In TypeScript, a class is a blueprint for creating objects that define a set of properties and methods that are common to all instances of the class. A class is declared using the class keyword, followed by the class name and a set of curly braces containing the class definition.

Syntax

The syntax of declaring a class in TypeScript is as follows −

class ClassName {
   // properties and methods
}

Example 1

Here we have declared a Car class that contains make, model and year attributes and their corresponding getter and setter methods.

class Car {
   private make: string;
   private model: string;
   private year: number;  
   constructor(make: string, model: string, year: number) {
      this.make = make;
      this.model = model;
      this.year = year;
   }  
   public getMake(): string {
      return this.make;
   }  
   public setMake(make: string): void {
      this.make = make;
   }  
   public getModel(): string {
      return this.model;
   }  
   public setModel(model: string): void {
      this.model = model;
   }  
   public getYear(): number {
      return this.year;
   }  
   public setYear(year: number): void {
      this.year = year;
   }
}

Object

In TypeScript, an object is an instance of a class that has its own set of properties and methods. An object is created using the new keyword, followed by the class name and any necessary arguments for the class constructor.

Syntax

The syntax for creating a class instance (object) −

let objectName = new ClassName(arguments);

Example 2

This creates an object named myCar with make: Toyota, model: Camry, and year: 2022

let myCar = new Car('Toyota', 'Camry', 2022);
console.log(myCar.getMake(), myCar.getModel(), myCar.getYear());

Constructor

In TypeScript, a constructor is a special method that is called when an object is created from a class. The constructor is used to initialize the object with default values. The constructor method is declared using the constructor keyword, followed by any necessary arguments.

Syntax

The syntax for writing a constructor function in TypeScript −

class ClassName {
   constructor(arguments) {
      // initialization code
   }
}

Example 3

This defines a constructor with an empty body and three parameters, namely: make, model, and year.

class Car {
   constructor(private make: string, private model: string, private year: number) {}
}

Inheritance

In TypeScript, inheritance is a mechanism that allows a class to inherit properties and methods from another class. A class that inherits from another class is called a subclass or derived class, and the class that is inherited from is called the superclass or base class. In TypeScript, inheritance is declared using the extends keyword.

Syntax

The syntax for creating a child class (sub-class) from a parent class (superclass) −

class SubclassName extends SuperclassName {
   // additional properties and methods
}

Example 4

Here the child class: ElectricCar, inherits the properties and methods from the parent class: Car. Additionally, it has its own property range and its getter and setter methods which are not present in the parent class.

class ElectricCar extends Car {
   private range: number;  
   constructor(make: string, model: string, year: number, range: number) {
      super(make, model, year);
      this.range = range;
   }
   public getRange(): number {
      return this.range;
   } 
   public setRange(range: number): void {
      this.range = range;
   }
}
const tesla = new ElectricCar("Tesla", "Model S", 2019, 300);
console.log(
   tesla.getMake(),
   tesla.getModel(),
   tesla.getYear(),
   tesla.getRange()
);

Polymorphism

In TypeScript, polymorphism is the ability of an object to take on many forms or types, allowing objects of different classes to be treated as if they were objects of a common class. Polymorphism is achieved through inheritance and interfaces. Here is an example demonstrating polymorphism

Example 5

Here, we have first created an interface Shape which is a blueprint similar to classes in TypeScript. It has a method-declared area. This interface is implemented twice, once for the Circle class and later on for the Rectangle class. In both of these classes, we have defined the body of the area function, which is defined differently, but the name of the function is exactly the same. This demonstrates the polymorphism property in OOP (same name but different forms).

interface Shape {
   area(): number;
}

class Circle implements Shape {
   constructor(private radius: number) {}
  
   public area(): number {
      return Math.PI * this.radius ** 2;
   }
}

class Rectangle implements Shape {
   constructor(private width: number, private height: number) {}
  
   public area(): number {
      return this.width * this.height;
   }
}
let shapes: Shape[] = [new Circle(5), new Rectangle(10, 20)];
shapes.forEach(shape => console.log(shape.area()));

On compiling, it will generate the following JavaScript code −

var Circle = /** @class */ (function () {
   function Circle(radius) {
      this.radius = radius;
   }
   Circle.prototype.area = function () {
      return Math.PI * Math.pow(this.radius, 2);
   };
   return Circle;
}());
var Rectangle = /** @class */ (function () {
   function Rectangle(width, height) {
      this.width = width;
      this.height = height;
   }
   Rectangle.prototype.area = function () {
      return this.width * this.height;
   };
   return Rectangle;
}());
var shapes = [new Circle(5), new Rectangle(10, 20)];
shapes.forEach(function (shape) { return console.log(shape.area()); });

Output

The above code will produce the following output −

78.53981633974483
200

Interface

In TypeScript, an interface is a blueprint for creating objects that define a set of properties and methods that must be implemented by any object that implements the interface. An interface is declared using the interface keyword, followed by the interface name and a set of curly braces containing the interface definition.

Syntax

interface InterfaceName {
   // properties and methods
}

Example 6

interface Person {
   firstName: string;
   lastName: string;
   age: number;
}

class Employee implements Person {
   constructor(public firstName: string, public lastName: string, public age: number, public jobTitle: string) {}
}
	
let Employee: Person = new Employee('John', 'Doe', 30, 'Software Engineer');
console.log(employee.firstName, employee.lastName, employee.age);

On compiling, it will generate the following JavaScript code −

var Employee = /** @class */ (function () {
   function Employee(firstName, lastName, age, jobTitle) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.jobTitle = jobTitle;
   }
   return Employee;
}());
var employee = new Employee('John', 'Doe', 30, 'Software Engineer');
console.log(employee.firstName, employee.lastName, employee.age);

Output

The above code will produce the following output −

John Doe 30

Here we have defined an interface named Person, and this interface is implemented using a class named Employee. Further, we create an instance of this class by passing arguments in the constructor function.

Conclusion

In conclusion, TypeScript's support for object-oriented programming allows developers to create well-structured and maintainable code. The language's features, including classes, objects, inheritance, polymorphism, interfaces, etc., make it easier to write and maintain complex applications. As a result, TypeScript has become a popular choice for building web applications, particularly those that require a high degree of organization and structure.

Updated on: 21-Aug-2023

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements