All academies
Roadmap/Intermediate

Level 9

Classes

Write fully typed classes: property declarations, constructors, access modifiers, parameter properties, inheritance, and implementing interfaces.

25 min read + quiz

Typed Class Basics

TypeScript classes are JavaScript classes with types layered on. The most visible addition: properties must be declared (with their types) in the class body before use. In plain JavaScript you can create properties on the fly inside any method; TypeScript requires the full shape of an instance to be known up front, which is what makes autocomplete and checking possible on every instance.

Strict mode adds definite-assignment checking: every declared property must be initialized, either at its declaration or in the constructor. If a property might never be assigned, the compiler flags it, closing a whole class of 'undefined property' bugs before they happen.

Methods are typed exactly like standalone functions: annotate the parameters, optionally annotate the return. Inside a method, 'this' is automatically typed as the class, so this.name and this.balance are fully checked.

class BankAccount {
  owner: string;
  balance: number;

  constructor(owner: string, openingBalance: number) {
    this.owner = owner;
    this.balance = openingBalance;
  }

  deposit(amount: number): number {
    this.balance += amount;
    return this.balance;
  }
}

const account = new BankAccount("Ada", 100);
console.log(account.deposit(50));  // 150

Declared, typed properties plus a constructor that definitely assigns them.

Access Modifiers: public, private, protected

TypeScript adds three visibility modifiers. public (the default) means accessible from anywhere. private restricts access to inside the class itself, so external code cannot read or write the member. protected sits in between: the class and its subclasses can access the member, but outside code cannot.

Private members are the heart of encapsulation. By making balance private and exposing deposit and withdraw methods, you guarantee every change to the balance goes through your validation logic; no code elsewhere can set account.balance = -1000 directly. The class controls its own invariants.

Important caveat: the private keyword is enforced only at compile time and disappears from the output, so determined JavaScript code can still reach the property at runtime. JavaScript's own #private fields (which TypeScript also supports) provide true runtime privacy. For most applications, compile-time enforcement is sufficient and the TypeScript keyword is more common.

class Counter {
  private count: number = 0;
  protected step: number = 1;

  increment(): number {
    this.count += this.step;
    return this.count;
  }
}

const c = new Counter();
console.log(c.increment());   // 1
console.log(c.increment());   // 2

// c.count;   // Error: 'count' is private, only visible inside Counter
// c.step;    // Error: 'step' is protected - Counter and subclasses only

private hides state from all outside code; protected shares it with subclasses only.

Parameter Properties and readonly

Declaring a property, naming a constructor parameter, and assigning one to the other is boilerplate TypeScript can eliminate. Putting an access modifier directly on a constructor parameter ('constructor(private name: string)') declares the property AND assigns it in one stroke. These are called parameter properties, and they can shrink a data-holding class dramatically.

The readonly modifier works on class properties just as it does in interfaces: the property can be set at declaration or in the constructor, then never reassigned. It combines with visibility ('private readonly') and is ideal for dependencies and configuration injected at construction time.

One style note: parameter properties are concise but slightly magical; the property declaration is easy to miss when skimming. Some teams embrace them everywhere (they are idiomatic in Angular and NestJS), while others prefer explicit declarations for important classes. Both are correct TypeScript.

// Without parameter properties: three mentions of each field.
class UserVerbose {
  private name: string;
  constructor(name: string) {
    this.name = name;
  }
}

// With parameter properties: one mention, same result.
class User {
  constructor(
    public readonly id: number,
    private name: string
  ) {}

  greet(): string {
    return "Hi, I am " + this.name + " (#" + this.id + ")";
  }
}

const u = new User(1, "Grace");
console.log(u.greet());
console.log(u.id);       // public readonly: readable, not writable

A modifier on a constructor parameter declares and assigns the property in one step.

Inheritance with extends

A class can extend one base class, inheriting its properties and methods. The subclass constructor must call super(...) before touching 'this', passing whatever the base constructor requires; TypeScript enforces both the call and its argument types. Subclasses can add new members and override inherited methods.

When overriding, the 'override' keyword is strongly recommended (and required with the noImplicitOverride compiler option). It documents intent and catches a nasty bug: if the base method is renamed or removed, an un-marked override silently becomes a new unrelated method, while a marked one produces an immediate compile error.

Inheritance is powerful but easy to overuse. Deep class hierarchies become rigid; TypeScript's structural typing and interface composition often model relationships more flexibly. A common rule of thumb: inherit for genuine is-a relationships with shared behavior, compose for everything else.

class Animal {
  constructor(public name: string) {}

  speak(): string {
    return this.name + " makes a sound";
  }
}

class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name);              // required before using 'this'
  }

  override speak(): string {  // 'override' catches renamed base methods
    return this.name + " barks";
  }
}

const rex = new Dog("Rex", "Beagle");
console.log(rex.speak());     // "Rex barks"
const animal: Animal = rex;   // a Dog is an Animal
console.log(animal.speak());  // still "Rex barks" - dynamic dispatch

extends, super, and the override keyword - with dynamic dispatch preserved.

Implementing Interfaces

The implements clause declares that a class satisfies an interface, and the compiler verifies every required member exists with a compatible type. Unlike extends, implements inherits nothing; it is purely a checked promise. A class can implement many interfaces while extending at most one class.

Why bother, given that structural typing would accept a matching class anyway? Because implements moves errors to the right place. Without it, a missing method surfaces wherever the instance is passed to something expecting the interface, possibly far from the class. With it, the class definition itself errors the moment it drifts from the contract.

This enables interface-first design: define the contract (say, PaymentProcessor), write functions against the interface, and provide multiple implementing classes: StripeProcessor, PayPalProcessor, and a MockProcessor for tests. Callers depend only on the interface, so implementations swap freely, which is the essence of dependency inversion.

interface Storage2 {
  save(key: string, value: string): void;
  load(key: string): string | undefined;
}

class MemoryStorage implements Storage2 {
  private data: Record<string, string> = {};

  save(key: string, value: string): void {
    this.data[key] = value;
  }

  load(key: string): string | undefined {
    return this.data[key];
  }
}

const store: Storage2 = new MemoryStorage();
store.save("theme", "dark");
console.log(store.load("theme"));   // "dark"

implements verifies the contract at the class definition, enabling swappable implementations.

Try it yourself

This lesson's example is preloaded in the playground — break it, fix it, extend it.

Open in playground

Check your understanding

Question 1 · Multiple choice

What is the difference between 'extends' and 'implements' on a class?

Question 2 · Find the error

This code fails to compile. Where is the error?

class Wallet {
  private balance: number = 0;

  deposit(amount: number): void {
    this.balance += amount;
  }
}

const w = new Wallet();
w.deposit(100);
console.log(w.balance);

Question 3 · Predict the output

What does this program print?

class Base {
  greet(): string {
    return "base";
  }
}

class Child extends Base {
  override greet(): string {
    return "child";
  }
}

const items: Base[] = [new Base(), new Child()];
console.log(items.map((i) => i.greet()).join(","));

Question 4 · Multiple choice

What does the parameter property 'constructor(private name: string) {}' do?

Question 5 · True or false

A property marked with TypeScript's 'private' keyword is completely inaccessible at runtime, just like JavaScript's #private fields.