Sikau

TypeScript · Day 20 · about 25 min

Classes in TypeScript

Access modifiers and implements.

Classes with contracts

TypeScript adds a few things to JavaScript classes: typed fields, public/private/readonly modifiers, and implements to promise that a class matches an interface.

Typed classes

interface Shape {
  area(): number;
  name: string;
}

class Circle implements Shape {
  readonly name = "circle";
  constructor(private radius: number) {}
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

const c = new Circle(2);
console.log(c.area().toFixed(2));
c.radius = 5;

class Square implements Shape {
  name = "square";
}

TypeScript's private is only checked at compile time. JavaScript's #private fields are enforced at runtime too. Both are fine — many teams prefer # for real privacy.

The rest of this lesson

  • Modifiers and parameter propertiesexplain
  • implements and abstract classesexplain
  • Error or not?predict
  • Modifier meaningsmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript