Lesson

TypeScript Classes

10 min reading
Free Course

TypeScript Classes: Access Modifiers, Contracts, and abstract

TypeScript enhances ES6 JavaScript classes with compile-time access modifiers (public, private, protected, readonly), parameter properties, interface implementation (implements), and abstract base classes.

These checks catch invalid internal property access during compilation while emitting clean standard JavaScript classes.

Parameter Properties and Access Modifiers

Adding public, private, protected, or readonly directly inside constructor parameters declares and assigns the class field in one step without boilerplate.

interface Printable {
  summary(): string;
}

class BankAccount implements Printable {
  constructor(
    public readonly owner: string,
    private balance: number = 0
  ) {}

  deposit(amount: number): number {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.balance += amount;
    return this.balance;
  }

  summary(): string {
    return `${this.owner}: $${this.balance.toFixed(2)}`;
  }
}

const acct = new BankAccount("Maya", 100);
acct.deposit(45);
console.log(acct.summary());

private vs JavaScript #private Fields

TypeScript's private keyword blocks external access only at compile time. JavaScript's #balance hash syntax enforces true privacy at runtime inside the V8/browser engine too.

Common Mistakes to Avoid

  • Assuming private hides properties in JSON.stringify() or DevTools: TypeScript private fields still exist as normal properties at runtime; use #field for real runtime encapsulation.
  • Forgetting override when overriding parent methods: Enable "noImplicitOverride": true and mark child overrides with override so renamed parent methods never leave dead code silently.
  • Calling abstract classes with new: Abstract classes serve only as blueprints for subclasses and cannot be instantiated directly.

Frequently Asked Questions

What is the difference between private and protected?

private restricts access strictly to the declaring class, while protected allows subclasses (extends) to read and call that member too.

Can a class implement multiple interfaces?

Yes. Write class Service implements Logger, Disposable { ... } separated by commas.

When should I use a plain object + functions instead of a class?

In React and functional TypeScript apps, plain typed objects and pure functions serialize cleanly to JSON and require less boilerplate unless you genuinely encapsulate mutable state.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum