Menu

Inheritance, Abstract Classes, and Interfaces

Lesson 3: Inheritance, Abstract Classes, and Interfaces

How do classes share behaviour?

Tool Purpose Can contain code?
extends Inherit fields and methods from a parent class Yes
abstract class A base class that cannot be created directly Yes, plus abstract members
abstract method Must be implemented by subclasses No
implements Promise that a class matches an interface No (interface is a contract only)
override Marks a method that replaces a parent method –

Example

interface PaymentProcessor {
  readonly method: string;
  charge(amount: number): Promise<{ success: boolean; reference: string }>;
}

abstract class BasePayment implements PaymentProcessor {
  abstract readonly method: string;

  async charge(amount: number) {
    this.validate(amount);
    const reference = await this.process(amount);
    return { success: true, reference };
  }

  protected validate(amount: number): void {
    if (amount <= 0) throw new Error('Invalid amount');
  }

  protected abstract process(amount: number): Promise<string>;
}

class UpiPayment extends BasePayment {
  readonly method = 'UPI';
  constructor(private upiId: string) { super(); }

  protected async process(amount: number): Promise<string> {
    return `UPI-${this.upiId}-${amount}`;
  }
}

class CodPayment extends BasePayment {
  readonly method = 'COD';

  protected override validate(amount: number): void {
    super.validate(amount);
    if (amount > 500000) throw new Error('COD limit is ₹5,000');
  }

  protected async process(): Promise<string> {
    return `COD-${Date.now()}`;
  }
}

const processors: PaymentProcessor[] = [new UpiPayment('asha@upi'), new CodPayment()];

How it works

  • new BasePayment() is an error because the class is abstract.
  • Each subclass must implement process, or the compiler reports it.
  • override makes intent explicit; with noImplicitOverride enabled, overriding without it is an error, which catches typos in method names.
  • The array is typed by the interface, so new processors can be added without changing checkout code.

Common mistakes

Mistake Effect Fix
Deep inheritance chains Hard to change and understand Prefer composition and small interfaces
Forgetting super() in a subclass constructor Error Call super(...) before using this
Expecting implements to add code Interfaces are contracts only Put shared code in a base class or helper

Key takeaways

  • Interfaces define contracts; abstract classes share code and enforce required methods.
  • Use override and keep inheritance shallow.

Try it: Add a CardPayment class that rejects amounts above ₹1,00,000 and returns a reference starting with CARD-.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details