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.