Object-Oriented Programming (OOP) in TypeScript

Object-Oriented Programming (OOP) in TypeScript enhances code reusability, readability, and maintainability. This blog covers the core OOP concepts in TypeScript with definitions, key features, implementation details, and code examples.

1. Class and Object

Definition:
Classes are blueprints for creating objects. Objects are instances of classes that hold data and methods.

Key Features:
Encapsulation of data, reusability of code, blueprint for objects.

Implementation in TypeScript:
Use the “class“ keyword to define a class and “new“ keyword to instantiate an object.

Example

2. Encapsulation

Definition:
Encapsulation restricts access to the internal details of an object, providing controlled interaction through public methods.

Key Features:
Use of access modifiers (public, private, protected) to control access to class properties and methods.

Implementation in TypeScript:
Use access modifiers to control visibility of class members.

Example

3. Inheritance

Definition:
Inheritance allows one class (child) to inherit properties and methods from another class (parent).

Key Features:
Reusability of parent class code, extends functionality.

Implementation in TypeScript:
Use the “extends “keyword to inherit from another class.

Example

4. Polymorphism

Definition:
Polymorphism allows objects of different types to be treated as objects of a common parent class.

Key Features:
Method overriding (runtime polymorphism), method overloading (compile-time polymorphism).

Implementation in TypeScript:
Use method overriding by redefining parent class methods in child classes.

Example

5. Abstraction

Definition:
Abstraction hides the complex implementation details and shows only essential features of an object.

Key Features:
Focus on "what" an object does rather than "how" it does it.

Implementation in TypeScript:
Use abstract classes or interfaces to achieve abstraction.

Example

Additional OOP Concepts

Interfaces
Interfaces define the structure of an object without implementation details.

Example

Constructor Overloading
TypeScript allows overloading by using optional parameters in constructors.

Example

Getters and Setters
Getters and setters encapsulate access to properties.

Example