ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

TypeScript Tutorial• 7 min read

Object-Oriented TypeScript & Access Modifiers

Constructors, public/private/protected visibility, readonly, and abstract classes

TypeScript extends ES6 classes with static type annotations, access modifiers, parameter properties, abstract classes, and interface implementation contracts.

Modifiers and Parameter Properties

public: Accessible from any scope (default).

protected: Accessible only within the declaring class and derived subclasses.

private: Accessible only within the declaring class at compile time.

#privateField: ECMAScript native private field enforced at true JavaScript runtime.

readonly: Prevents assignment to a property after construction.

abstract class: Base class that cannot be instantiated directly and serves as a blueprint for subclasses.

Abstract Classes and Parameter Properties
abstract class PaymentProcessor {
  // Parameter property: automatically assigns this.apiKey and this.isLive
  constructor(
    protected readonly apiKey: string,
    public readonly isLive: boolean = false
  ) {}

  // Abstract method must be implemented by subclasses
  abstract processPayment(amount: number): Promise<boolean>;

  public logTransaction(amount: number): void {
    console.log(`[${this.isLive ? 'LIVE' : 'SANDBOX'}] Processed $${amount}`);
  }
}

class StripeProcessor extends PaymentProcessor {
  async processPayment(amount: number): Promise<boolean> {
    console.log(`Contacting Stripe API with key ${this.apiKey.substring(0, 4)}*** for $${amount}`);
    this.logTransaction(amount);
    return true;
  }
}

const gateway = new StripeProcessor("sk_live_998127391823", true);
gateway.processPayment(250);
Parameter properties in constructor arguments eliminate repetitive assignment boilerplate.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the effect of prefixing a constructor parameter with "private readonly"?