Classes

What

Classes in TypeScript provide a blueprint for creating objects with defined properties and behaviors, similar to standard JavaScript but with added static type safety.

How

You declare properties at the top of the class and provide type annotations for parameters in the constructor and methods:

class Hero {
  name: string;
  health: number;

  constructor(name: string, health: number) {
    this.name = name;
    this.health = health;
  }

  attack(damage: number): void {
    console.log(`${this.name} attacks for ${damage} damage!`);
  }
}

const geralt = new Hero("Geralt", 100);

Why

Typing classes ensures that all properties are correctly initialized and that methods are called with the expected arguments. It brings the robustness of object-oriented programming to JavaScript, making large-scale application logic easier to manage and refactor.

Summary

TypeScript classes combine the structure of blueprints with the safety of a strong type system.