Explorer
Typescript

TypeScript OOP: Classes, Inheritance & Abstract Classes

Learn how TypeScript uses classes, access modifiers, inheritance, and composition to organize reusable application logic.

Imagine you're building a food-ordering application.

Every tea order has a flavor, price, and sugar level. It also needs operations such as updating sugar, calculating prices, and preparing drinks.

You could create separate variables and functions for everything. But as the application grows, managing them becomes difficult.

What if we could group related data and behavior into one reusable structure?

That's the idea behind Object-Oriented Programming (OOP).

TypeScript supports JavaScript's class system and adds static type checking, access modifiers, and abstract classes to help developers model objects more clearly.

1. Classes and Constructors

A class is a blueprint for creating objects that contain related properties and methods.

JAVASCRIPT
class Tea {
  flavor: string;
  price: number;

  constructor(flavor: string, price: number) {
    this.flavor = flavor;
    this.price = price;
  }

  describe(): string {
    return `${this.flavor} tea costs ₹${this.price}`;
  }
}

const chai = new Tea("Masala", 25);

console.log(chai.describe());
// Masala tea costs ₹25

Here:

  • class Tea defines the structure and behavior.

  • constructor() initializes each new instance.

  • this refers to the instance on which the method is called.

  • new Tea() creates an object.

TypeScript checks that required fields are initialized when strict property initialization is enabled. Fields can be initialized directly or assigned in the constructor.

Constructor parameter properties

TypeScript also provides shorthand for declaring and initializing class properties:

JAVASCRIPT
class Tea {
  constructor(
    public flavor: string,
    public price: number
  ) {}
}

This is equivalent in purpose to explicitly declaring the fields and assigning them inside the constructor.

Remember: A class groups data and behavior. A constructor initializes the object when an instance is created.

2. Access Modifiers: public, private and protected

Not every class property should be accessible from outside.

For example, users might be allowed to see the price of a tea but shouldn't directly modify internal accounting data.

TypeScript provides three access modifiers.

Modifier

Inside class

Subclass

Outside class

public

Yes

Yes

Yes

private

Yes

No

No

protected

Yes

Yes

No

2.1 public — Accessible everywhere

JAVASCRIPT
class Tea {
  public flavor = "Masala";
}

const tea = new Tea();

console.log(tea.flavor); // Valid

public is the default visibility modifier, so writing it is optional.

2.2 private — Accessible only inside the class

JAVASCRIPT
class Tea {
  private costPrice = 15;

  getCost(): number {
    return this.costPrice;
  }
}

const tea = new Tea();

console.log(tea.getCost()); // 15

// tea.costPrice; // Type error

Private members cannot be directly accessed from outside the declaring class or from subclasses.

2.3 protected — Accessible inside subclasses

JAVASCRIPT
class Drink {
  protected shopName = "Chai Cafe";
}

class Tea extends Drink {
  showShop(): string {
    return this.shopName;
  }
}

const tea = new Tea();

console.log(tea.showShop()); // Chai Cafe

// tea.shopName; // Type error

A subclass can access protected members inherited from its parent.

TypeScript private vs JavaScript #private

There's an important distinction.

JAVASCRIPT
class Account {
  private balance = 100;
  #pin = 1234;
}
  • TypeScript private is primarily a compile-time access restriction.

  • JavaScript #pin is a native private field with runtime-enforced access restrictions.

If you need actual JavaScript runtime privacy, #private fields are the stronger option.

3. readonly: Preventing Reassignment

Some class properties should not change after initialization.

For example, a unique order ID should remain the same throughout the object's lifecycle.

JAVASCRIPT
class TeaOrder {
  readonly orderId: string;

  constructor(orderId: string) {
    this.orderId = orderId;
  }
}

const order = new TeaOrder("ORD-101");

// order.orderId = "ORD-102"; // Type error

A readonly field can be initialized at declaration or assigned within the constructor.

After initialization, TypeScript prevents reassignment through that property.

Important: readonly is enforced by TypeScript's type checker. It doesn't automatically freeze the object at runtime.

4. Getters and Setters: Controlled Property Access

Sometimes we want to expose a property while controlling how it is read or changed.

Imagine allowing customers to update the sugar level of their tea, but restricting it to a valid range.

JAVASCRIPT
class Tea {
  private _sugarLevel = 2;

  get sugar(): number {
    return this._sugarLevel;
  }

  set sugar(value: number) {
    if (value < 0 || value > 5) {
      throw new Error("Sugar must be between 0 and 5");
    }

    this._sugarLevel = value;
  }
}

const tea = new Tea();

tea.sugar = 3;           // Calls setter
console.log(tea.sugar); // Calls getter: 3

Here:

  • get reads the value.

  • set controls how the value is updated.

  • Validation prevents invalid assignments at runtime.

This demonstrates encapsulation: keeping internal state controlled through a defined interface.

Use getters and setters when you need validation, computed values, or controlled access. Simple public properties don't always need them.

5. Static Members: Belonging to the Class

Normally, properties belong to individual objects.

But some values should be shared at the class level.

JAVASCRIPT
class Tea {
  static shopName = "Chai Cafe";

  constructor(public flavor: string) {}
}

console.log(Tea.shopName); // Chai Cafe

Notice that we access shopName through Tea, not through an instance.

JAVASCRIPT
const tea = new Tea("Masala");

// tea.shopName; // Type error

Static members are useful for shared constants, factory methods, and class-level utilities.

Remember: Instance members belong to objects. Static members belong to the class itself.

6. Inheritance: Reusing Parent Class Behavior

Inheritance allows one class to reuse or extend the behavior of another.

It represents an is-a relationship.

For example, Tea is a kind of Drink.

JAVASCRIPT
class Drink {
  constructor(public name: string) {}

  serve(): void {
    console.log(`Serving ${this.name}`);
  }
}

class Tea extends Drink {
  brew(): void {
    console.log(`Brewing ${this.name}`);
  }
}

const tea = new Tea("Masala Tea");

tea.brew();  // Brewing Masala Tea
tea.serve(); // Serving Masala Tea

The Tea class inherits the public behavior of Drink through extends.

Method overriding

A subclass can provide its own version of an inherited method.

JAVASCRIPT
class SpecialTea extends Drink {
  override serve(): void {
    console.log(`Serving special ${this.name}`);
  }
}

The override keyword makes the intention explicit and helps TypeScript detect incorrect overrides.

Inheritance is useful when classes share a genuine relationship and common behavior.

However, deep inheritance hierarchies can make applications difficult to maintain.

7. Abstract Classes: Defining a Common Contract

Imagine your application supports tea, coffee, and juice.

Every drink must implement its own preparation logic, but you also want to share common functionality.

An abstract class provides a base structure that cannot be instantiated directly.

JAVASCRIPT
abstract class Drink {
  constructor(public name: string) {}

  abstract prepare(): void;

  serve(): void {
    console.log(`Serving ${this.name}`);
  }
}

class Tea extends Drink {
  prepare(): void {
    console.log(`Brewing ${this.name}`);
  }
}

const tea = new Tea("Masala Tea");

tea.prepare();
tea.serve();

The abstract method prepare() has no implementation in the base class.

Concrete subclasses must implement it.

You cannot directly create an instance using new Drink() in type-checked TypeScript.

Abstract class vs interface

Abstract class

Interface

Can contain implemented methods

Defines type contracts

Can hold shared state

Doesn't create runtime state

Supports constructors

No implementation constructor

Exists as a JavaScript class at runtime

Erased from JavaScript output

When to use an abstract class: When related subclasses need both a common contract and shared implementation.

Use an interface when you only need to define a contract without sharing class implementation.

8. Composition vs Inheritance

One of the most useful OOP design decisions is choosing between inheritance and composition.

Inheritance: Is-a relationship

JAVASCRIPT
class Drink {
  serve() {
    console.log("Serving drink");
  }
}

class Tea extends Drink {}

Tea is a Drink.

Composition: Has-a relationship

Composition means building a class using other objects.

JAVASCRIPT
class Heater {
  heatWater(): void {
    console.log("Heating water...");
  }
}

class TeaMaker {
  constructor(private heater: Heater) {}

  makeTea(): void {
    this.heater.heatWater();
    console.log("Brewing tea...");
  }
}

const maker = new TeaMaker(new Heater());

maker.makeTea();

Here, TeaMaker has a Heater.

It doesn't need to inherit from Heater because a tea maker isn't a type of heater.

Why composition is useful

Composition lets us replace individual dependencies without redesigning an entire inheritance hierarchy.

For example, TeaMaker could use a different heater implementation if its contract remained compatible.

This is particularly useful in backend services, dependency injection, and application architectures where components need to be independently testable.

Production tip: Prefer composition when objects need flexible, replaceable dependencies. Use inheritance when a clear subtype relationship and shared base behavior genuinely exist.

9. Common Mistakes

Mistake

Better approach

Making every property public

Control access where necessary

Assuming private guarantees runtime privacy

Use JavaScript #private when needed

Using getters/setters for every simple field

Add them when behavior or validation is required

Using deep inheritance hierarchies

Consider composition

Using abstract classes for type-only contracts

Consider interfaces

Assuming readonly freezes objects

Remember it provides static protection

10. TypeScript Interview Questions

Q1. What is the purpose of a constructor?

A constructor initializes a class instance. It can receive parameters, assign properties, and set up the object's initial state.

Q2. What is the difference between public, private, and protected?

public members are accessible everywhere. private members are accessible within the declaring class. protected members are accessible within the class and its subclasses.

Q3. What is the difference between TypeScript private and JavaScript #private?

TypeScript's private modifier provides static access restrictions, while JavaScript #private fields enforce runtime privacy.

Q4. What is an abstract class?

An abstract class defines a base structure that cannot be directly instantiated in type-checked TypeScript. It can provide shared implementations and abstract members that concrete subclasses must implement.

Q5. What is the difference between static and instance members?

Static members belong to the class itself, while instance members belong to individual objects created from the class.

Q6. Why is composition often preferred over inheritance?

Composition allows classes to use replaceable dependencies without becoming tightly coupled through a deep inheritance hierarchy, improving flexibility and testability.

11. Quick Revision Notes

Core concepts

Concept

Remember

class

Blueprint for creating objects

constructor

Initializes an instance

this

Refers to the current instance

public

Accessible from anywhere

private

Accessible within declaring class

protected

Accessible in class and subclasses

readonly

Prevents reassignment through type checking

get / set

Controlled property access

static

Member belongs to the class

extends

Class inheritance

override

Explicitly overrides inherited member

abstract

Defines non-instantiable base class contracts

Composition

Has-a relationship

Inheritance

Is-a relationship

Essential syntax

Class and constructor

JAVASCRIPT
class User {
  constructor(public name: string) {}
}

Private field

JAVASCRIPT
class Account {
  #balance = 100;
}

Static member

JAVASCRIPT
class Config {
  static appName = "ConsistCode";
}

Inheritance

JAVASCRIPT
class Animal {}
class Dog extends Animal {}

Abstract class

JAVASCRIPT
abstract class Shape {
  abstract area(): number;
}

Composition

JAVASCRIPT
class Engine {}

class Car {
  constructor(private engine: Engine) {}
}

Five things to remember

  1. Classes combine state and behavior into reusable objects.

  2. Access modifiers control which parts of a class can be accessed.

  3. static members belong to the class rather than individual instances.

  4. Abstract classes define common behavior and required subclass implementations.

  5. Prefer composition when dependencies need to be flexible and replaceable.

Final takeaway

Object-Oriented Programming helps organize complex applications by grouping related data and behavior.

TypeScript strengthens JavaScript's class system through static type checking, access modifiers, and abstract contracts.

However, good OOP is not about creating more classes or inheritance layers.

Use classes where they make responsibilities clearer, encapsulate state when necessary, and prefer simple, flexible designs over unnecessary complexity.


Further Reading

Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.