Tutorials / TypeScript: Beginner to Advanced / Classes in TypeScript

Classes in TypeScript

16 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

Classes you already know, with types

If you know JavaScript classes, TypeScript adds three things: types for properties, access modifiers, and implements and abstract for contracts.

class BankAccount {
  readonly owner: string;
  private balance: number;

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

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

  getBalance(): number {
    return this.balance;
  }
}

const account = new BankAccount("Ali", 1000);
account.deposit(500);
console.log(account.owner, account.getBalance()); // Ali 1500
// account.balance = 0;       // Error: 'balance' is private
// account.owner = "Bilal";   // Error: read-only

Properties must be declared in the class body with a type. Under strict, a property with no initial value must be set in the constructor, or the compiler complains that it is "not definitely assigned".

Access modifiers

ModifierVisible to
public (the default)Everyone
protectedThe class and its subclasses
privateThe class only
readonlyEveryone can read, only the constructor can set

private in TypeScript is a compile-time check. At runtime, the property is a normal one that any JavaScript code can read. If you need real runtime privacy, use JavaScript's #name private fields, which TypeScript supports as well:

class Counter {
  #count = 0;

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

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

Parameter properties

A common pattern is to receive constructor parameters and copy them into properties. TypeScript has a shortcut. Put a modifier in front of the parameter, and it is declared and assigned for you:

class Product {
  constructor(
    public readonly id: number,
    public name: string,
    private cost: number,
  ) {}

  margin(price: number): number {
    return price - this.cost;
  }
}

const p = new Product(1, "Keyboard", 2500);
console.log(p.name, p.margin(3500)); // Keyboard 1000

That is the whole class. Some teams like the shortness, others find it hides what the class has. Be consistent with your team. Note that parameter properties are one of the TypeScript features that need a real compiler. Pure type stripping cannot handle them.

Implementing interfaces

A class can promise to follow an interface with implements. The compiler checks that it does:

interface Printable {
  print(): string;
}

class Invoice implements Printable {
  constructor(private total: number) {}

  print(): string {
    return `Invoice total: Rs. ${this.total}`;
  }
}

class Receipt implements Printable {
  print(): string {
    return "Thank you for your purchase";
  }
}

const docs: Printable[] = [new Invoice(2500), new Receipt()];
for (const doc of docs) {
  console.log(doc.print());
}

The array holds different classes, and our code only depends on the interface. That makes it easy to add a new kind of document later. Remember that implements only checks; it does not copy any code into the class.

Inheritance and abstract classes

abstract class Shape {
  constructor(public readonly name: string) {}

  abstract area(): number;       // subclasses must implement this

  describe(): string {
    return `${this.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super("Circle");
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

class Rectangle extends Shape {
  constructor(private width: number, private height: number) {
    super("Rectangle");
  }

  override area(): number {
    return this.width * this.height;
  }
}

// const s = new Shape("x");   // Error: cannot create an instance of an abstract class
console.log(new Circle(1).describe());
console.log(new Rectangle(2, 3).describe());

An abstract class is a partial base class that cannot be created directly. It can mix finished methods like describe with abstract ones that children must supply. The override keyword is optional, but it asks the compiler to confirm that the parent really has that method, which catches typos. Turn on the noImplicitOverride option to require it.

Static members and getters

class IdGenerator {
  private static next = 1;

  static create(): number {
    return IdGenerator.next++;
  }
}

class Temperature {
  constructor(private celsius: number) {}

  get fahrenheit(): number {
    return this.celsius * 9 / 5 + 32;
  }
}

console.log(IdGenerator.create(), IdGenerator.create());   // 1 2
console.log(new Temperature(100).fahrenheit);              // 212

Structural typing applies to classes too

Two classes with the same public shape are interchangeable in TypeScript. Private and protected members change that. Only the original class satisfies a type that has private members. This is why a type with private fields behaves like a "nominal" type.

Composition over inheritance

The same advice as in JavaScript. Deep class trees are brittle. For many cases, a plain function or a small object that you pass in is simpler than a base class. A class is a good fit when you have state that goes with behaviour, such as an account, a connection or a cache.

Common mistakes

  • **Treating private as security.** It disappears at runtime. Use #private when it matters.
  • **Forgetting super() first in a subclass constructor.** The compiler will tell you.
  • Uninitialised properties. Strict mode flags them. Initialise them, make them optional, or assign in the constructor.
  • **Passing a method as a callback and losing this.** Same problem as in JavaScript. Use an arrow function or an arrow property.
  • Inheriting for code reuse only. Prefer composition.

Try it yourself

  1. Write a Stack<T>-like class for numbers with push, pop and a read-only size getter, using a private array.
  2. Create an interface Logger with log(message: string): void, and two classes that implement it.
  3. Turn Shape into an abstract class with a third subclass Triangle.
  4. Convert the Product example to use #cost instead of a TypeScript private modifier, and note what else must change.
typescript
class BankAccount {
  readonly owner: string;
  private balance: number;

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

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

  getBalance(): number {
    return this.balance;
  }
}

const account = new BankAccount("Ali", 1000);
account.deposit(500);
console.log(account.owner, account.getBalance()); // Ali 1500
// account.balance = 0;       // Error: 'balance' is private
// account.owner = "Bilal";   // Error: read-only

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account