DEV Community

Khafido Ilzam
Khafido Ilzam

Posted on

Implement OOP using TypeScript

Let’s learn how to implement all OOP principles in TypeScript.

  • Classes & Objects
  • Encapsulation
  • Abstraction & Interface
  • Inheritance
  • Polymorphism

Class and Object

A class is a blueprint, and objects are instances of the class.

Class and Object

Object instance

Encapsulation

Encapsulation = hide internal data, expose only what is needed.
Use private, protected, and public.

Abstraction

Abstraction = hide complexity and expose only what the user needs.
Use abstract classes or interfaces. Interfaces define shape, and classes can implement them.

You cannot create an object from it, but it can have abstract methods (no body) and normal methods. The child must implement (override) the abstract method.

A class can implement multiple interfaces. But a class can extend only one class

Interfaces do NOT contain implementation. Classes must provide the implementation

Inheritance

A class can inherit methods or data from another class.

Polymorphism

Polymorphism = same method name, different behavior.

Full Example Code:
https://snipsave.com/view-snippet?user=khafidoilzam&snippet_id=Fp13KgLloQpTnToegf

Top comments (0)