TypeScript theorytheory 0/50 · 0%
Foundations · easy

11. Classes: fields, methods, constructors

Object-oriented building blocks with typed members.

Classes declare typed fields and methods, plus a `constructor` for initialization. Parameter properties let you declare and assign a field in one step by adding a modifier to a constructor parameter.

ts
class Wallet {
  balance: number;
  constructor(public address: string, initial: number = 0) {
    this.balance = initial;
  }
  deposit(amount: number): void {
    this.balance += amount;
  }
}

const w = new Wallet("0xabc", 100);
w.deposit(50);

Here `public address: string` in the constructor both declares `this.address` and assigns it from the argument, avoiding boilerplate. Fields can also have default values and `readonly` modifiers.

Check your understanding

  1. 1. What does `constructor(public address: string)` do?

  2. 2. What return type does a method with no return value typically have?

  3. 3. Can a class field have a default value?