TSTypeScript
IntermediateLesson 8 of 15

Classes in TypeScript – TypeScript

Access modifiers, parameter properties, abstract and implements.

TypeScript adds types for fields and the modifiers public, private, protected and readonly to JavaScript classes. The modifiers only apply at compile time (for real privacy you use #field).

class Konto {
  readonly inhaber: string;
  private saldo = 0;
  protected iban: string;

  constructor(inhaber: string, iban: string) {
    this.inhaber = inhaber;
    this.iban = iban;
  }
  einzahlen(betrag: number): this {
    if (betrag <= 0) throw new RangeError("Amount must be positive");
    this.saldo += betrag;
    return this;
  }
  get stand(): number {
    return this.saldo;
  }
}

const k = new Konto("Ada", "DE00 1234").einzahlen(50);
console.log(k.stand);
// k.saldo = 1000;      // Error: 'saldo' is private

Parameter properties save boilerplate: a modifier in front of the constructor parameter creates the field and assigns it. override makes sure you really are overriding a method of the base class:

class Tier {
  constructor(protected readonly name: string) {}
  sprich(): string {
    return this.name + " makes a sound";
  }
}
class Hund extends Tier {
  override sprich(): string {
    return this.name + " says Woof!";
  }
}
console.log(new Hund("Rex").sprich());

Abstract classes provide a basic skeleton, interfaces describe a contract that classes fulfil with implements:

abstract class Form {
  abstract flaeche(): number;
  beschreibe(): string {
    return "Area: " + this.flaeche().toFixed(2);
  }
}
class Quadrat extends Form {
  constructor(private seite: number) { super(); }
  flaeche(): number { return this.seite ** 2; }
}
// new Form();          // Error: Cannot create an instance of an abstract class
console.log(new Quadrat(3).beschreibe());

interface Speicherbar {
  speichere(): void;
}
class Notiz implements Speicherbar {
  speichere(): void { console.log("saved"); }
}
Warningprivate is only a compiler check. At runtime anyone can access the field. For truly protected data use JavaScript's #field.
TipSet noImplicitOverride in tsconfig.json so that every override needs an override – this catches mistakes when you rename base-class methods.